How to convert POJO to XML using Jackson

I am looking for the best solution to convert POJO or JSON to XML with all attributes in the right places. At the moment, Jackson looks the most convenient way. I can serialize POJO to XML without attributes.

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;
        }
    }
}

Here is the code:

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));
}

And now he returns it

<TestUser xmlns="">
    <product>
        <username>FOO</username>
        <fullname>FOO BAR</fullname>
        <email>foobar@foobar.com</email>
        <enabled>true</enabled>
    </product>
</TestUser>

Ok, but I need a variable enabledfor the attribute username, and then I need to add the xmlns and xsi attributes to the root element so that the XML result looks like this:

<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> 

I found several examples using @JacksonXmlProperty, but only adds an attribute to the root element.

thanks for the help

+4
source share
1 answer

: . ; , , , @JsonRootName (schema=URL?), ?

:

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

-, ; , .

+1

All Articles