如何使用Jackson将POJO转换为XML
发布时间:2020-12-16 22:45:53 所属栏目:百科 来源:网络整理
导读:我正在寻找最佳解决方案如何将POJO或 JSON转换为XML,并将所有atttributes转换为正确的位置.目前,杰克逊看起来是最方便的方式.我能够将POJO序列化为没有属性的XML. POJO TestUser public class TestUser extends JsonType{ @JsonProperty("username") private
我正在寻找最佳解决方案如何将POJO或
JSON转换为XML,并将所有atttributes转换为正确的位置.目前,杰克逊看起来是最方便的方式.我能够将POJO序列化为没有属性的XML.
POJO TestUser public class TestUser extends JsonType { @JsonProperty("username") private final String username; @JsonProperty("fullname") private final String fullname; @JsonProperty("email") private final String email; @JsonProperty("enabled") private final Boolean enabled; @JsonCreator public TestUser( @JsonProperty("username") String username,@JsonProperty("fullname") String fullname,@JsonProperty("email") String email,@JsonProperty("enabled") Boolean enabled) { this.username = username; this.fullname = fullname; this.email = email; this.enabled = enabled; } @JsonGetter("username") public String getUsername() { return username; } @JsonGetter("fullname") public String getFullname() { return fullname; } @JsonGetter("email") public String getEmail() { return email; } @JsonGetter("enabled") public Boolean getEnabled() { return enabled; } } } 这是代码: public void testJsonToXML() throws JsonParseException,JsonMappingException,IOException { String jsonInput = "{"username":"FOO","fullname":"FOO BAR","email":"foobar@foobar.com","enabled":"true"}"; ObjectMapper jsonMapper = new ObjectMapper(); TestUser foo = jsonMapper.readValue(jsonInput,TestUser.class); XmlMapper xmlMapper = new XmlMapper(); System.out.println(xmlMapper.writer().with(SerializationFeature.WRAP_ROOT_VALUE).withRootName("product").writeValueAsString(foo)); } 现在它又回来了 <TestUser xmlns=""> <product> <username>FOO</username> <fullname>FOO BAR</fullname> <email>foobar@foobar.com</email> <enabled>true</enabled> </product> </TestUser> 哪个好,但是我需要启用变量作为username的属性然后我需要将xmlns和xsi属性添加到根元素,因此XML结果看起来像这样 <TestUser xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="testUser.xsd"> <product> <username enabled="true">FOO</username> <fullname>FOO BAR</fullname> <email>foobar@foobar.com</email> </product> </TestUser> 我找到了一些使用@JacksonXmlProperty的例子,但它只将属性添加到根元素. 感谢帮助 解决方法
有趣的问题:注入额外的数据.目前没有这样做的功能;但我认为可以在@JsonRootName(schema = URL?)中添加一个新属性,允许添加模式映射或映射?
我继续提交这个: https://github.com/FasterXML/jackson-dataformat-xml/issues/90 添加应该起作用的东西;随时添加评论,建议. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |