usr_11
usr_11

Reputation: 576

Create Xml in java fasterxml

I am using fasterxml.jackson to create xml using POJO.

I am expecting output as below:

<Customer xmlns="">
    <firstname>FirstNameA</firstname>
    <middlename>LastNameA</middlename>
</Customer>

But getting output as:
<Customer xmlns="">
    <item>
        <firstname>FirstNameA</firstname>
        <middlename>LastNameA</middlename>
    </item>
</Customer>

why is it appending <item> tag. I have not appended <item> tag anywhere, but output is showing <item> tag.what is wrong in my code?

This is POJO

    @JacksonXmlRootElement(localName = "Customer")
    public class Customer {  
        @JacksonXmlProperty(localName="firstname")
        private String firstname;

        @JacksonXmlProperty(localName="middlename")
        private String middlename;


        public Customer(String firstname, String middlename) {
            this.firstname = firstname;
            this.middlename = middlename;
        }
}

// code to create xml
    ObjectMapper xmlMapper = new XmlMapper();
            JacksonXmlModule module = new JacksonXmlModule();
            module.setDefaultUseWrapper(false);
            Customer[] cust = new Customer[]{new Customer("FirstNameA", "LastNameA")};
            try {
                String xml = xmlMapper.writeValueAsString(cust);
                return xml;
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }

Upvotes: 0

Views: 1320

Answers (1)

marco
marco

Reputation: 681

customer in your code is an array, and you cannot add more than one item in the xml style you posted:

<Customer xmlns="">
    <firstname>FirstNameA</firstname>
    <middlename>LastNameA</middlename>
</Customer>

just replace in your code:

Customer cust = new Customer("FirstNameA", "LastNameA");

Upvotes: 1

Related Questions