2017-10-12 77 views
0

我正在使用fasterxml.jackson使用POJO創建xml。在java中創建xml更快xml

我期待輸出如下:

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

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

爲什麼會追加<item>標籤。我沒有在任何地方添加<item>標記,但輸出顯示爲<item>標記。我的代碼中存在哪些錯誤?

這是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(); 
      } 

回答

1

客戶在你的代碼是一個數組,你不能在您發佈的XML樣式添加多個項目:

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

只需更換你的代碼:

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

感謝您的解決方案。 –

+0

只需點擊向上箭頭,告訴其他用戶它是正確的解決方案。 – marco

+0

我已經upvoted你的回答 –