将XML属性映射到Java属性

发布于 2025-02-09 07:09:59 字数 408 浏览 1 评论 0原文

Is there a way to map xml attributes to Java attributes using Jackson Faster xml.
Sample xml
<student>
 <details>
  <element key="firstName" value="John" />
  <element key="lastName" value="Doe" />
 </details>
</student>

以上XML需要映射到Java类以下。

public class Student {
private String firstName;
private String lastName;
}
Is there a way to map xml attributes to Java attributes using Jackson Faster xml.
Sample xml
<student>
 <details>
  <element key="firstName" value="John" />
  <element key="lastName" value="Doe" />
 </details>
</student>

The above xml needs to be mapped to below Java class.

public class Student {
private String firstName;
private String lastName;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

平定天下 2025-02-16 07:09:59

对于这种情况,我编写了静态代码:

public static <T> T unmarshall(String xml, Class<T> clazz) throws JAXBException {
        JAXBContext jc = JAXBContext.newInstance(clazz);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        T obj = clazz.cast(unmarshaller.unmarshal(new StringReader(xml)));
        return obj;
    }

也注释您的DTO:

@Getter
@Setter
@XmlRootElement(name = "<SomeName>")
@XmlAccessorType(XmlAccessType.FIELD)
public class Student {
private String firstName;
private String lastName;
}

使用此方法后,您可以使用它来序列化数据:

Student studentResponse = (Student) unmarshall(response, Student.class);

for such cases, I have written a static piece of code:

public static <T> T unmarshall(String xml, Class<T> clazz) throws JAXBException {
        JAXBContext jc = JAXBContext.newInstance(clazz);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        T obj = clazz.cast(unmarshaller.unmarshal(new StringReader(xml)));
        return obj;
    }

Also annotate your DTO with:

@Getter
@Setter
@XmlRootElement(name = "<SomeName>")
@XmlAccessorType(XmlAccessType.FIELD)
public class Student {
private String firstName;
private String lastName;
}

After you have this method, you can use it to serialize your data:

Student studentResponse = (Student) unmarshall(response, Student.class);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文