如何使用Jackson将POJO转换为XML

4
我希望您能提供最佳解决方案,将POJO或JSON转换为XML,并将所有属性放置在正确的位置。目前,Jackson似乎是最方便的方式。我可以将POJO序列化为不带属性的XML。
POJO测试用户
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>

这很好,但我需要将变量enabled作为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的例子,但它只将属性添加到根元素。
谢谢帮助。

你正在扩展的 TestUser 中,JsonType 的完整包名称是什么? - Chaitanya
1个回答

1
有趣的问题:注入额外数据。目前没有这样的功能;但我认为可以添加一个新属性到@JsonRootName中(schema=URL?),允许添加模式映射或多个映射?
我已经提交了这个问题:

https://github.com/FasterXML/jackson-dataformat-xml/issues/90

如果您有任何能够正常工作的补充,请随时添加评论和建议。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接