2017-04-14 48 views
0

我正在學習使用Jackson來序列化XML。我的課堂結構如下。使用Jackson將對象序列化爲XML

class City { 
    @JacksonXmlProperty(localName = "CityName") 
    String cityName; 

    public City(String cityName) { 
     this.cityName = cityName; 
    } 

    public String getcityName() { 
     return cityName; 
    } 

    public void setcity(String cityName) { 
     this.cityName = cityName; 
    } 
} 

@JacksonXmlRootElement(localName = "Person") 
class Person { 
    @JacksonXmlProperty(localName = "name") 
    private String name; 

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

    @JacksonXmlProperty(localName = "city") 
    private List<City> city; 

    public Person() { } 

    Person(String name, String age, List<City> city) { 
     this.name = name; 
     this.age = age; 
     this.city = city; 
    } 

    public String getname() { 
     return name; 
    } 

    public String getage() { 
     return age; 
    } 

    public List<City> getcity() { 
     return city; 
    } 

    public void setname(String name) { 
     this.name = name; 
    } 

    public void setage(String age) { 
     this.age = age; 
    } 

    public void setcity(List<City> city) { 
     this.city = city; 
    } 
} 

當我試圖序列使用傑克遜一類爲XML,我得到兩個標籤爲<city>

public class App 
{ 
    public static void main(String[] args) 
    { 
     try { 
      XmlMapper xmlMapper2 = new XmlMapper(); 
      Person p = new Person(); 
      City c1 = new City("abc"); 
      City c2 = new City("def"); 
      City c3 = new City("ghi"); 
      List<City> cityList = new ArrayList<City>(); 
      cityList.add(c1); 
      cityList.add(c2); 
      cityList.add(c3); 
      p.setname("setattr"); 
      p.setage("55"); 
      p.setcity(cityList); 
      xmlMapper2.enable(SerializationFeature.INDENT_OUTPUT); 
      String respPerson = xmlMapper2.writeValueAsString(p); 
      System.out.println(respPerson); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

這是我得到的輸出。

<Person><name>setattr</name><age>55</age><city><city><CityName>sfo</CityName></city><city><CityName>sjc</CityName></city><city><CityName>sea</CityName></city></city></Person> 

你能幫我理解爲什麼我會得到城市的兩個標籤,我該如何修復它?

我想輸出是這樣的,

<Person><name>setattr</name><age>55</age><city><CityName>sfo</CityName><CityName>sjc</CityName><CityName>sea</CityName></city></Person> 
+0

你能告訴我這是重複的嗎?我已經檢查過這個帖子。任何關於如何修復我的代碼以使其工作的建議? – Anit

+0

使用@JacksonXmlElementWrapper(useWrapping = false),我仍然可以看到標籤被每個標籤包圍。相反,我只需要一個圍繞所有城市名稱的標記 – Anit

回答

1

你的城市的名單。傑克遜對名單本身和名單成員都使用「城市」。如果您將本地名稱更改爲「城市」,您可能會更喜歡這些結果。

不幸的是,這不是正確的答案。看來,正確的答案是https://stackoverflow.com/a/27144625/131433

+0

我更改了「localName = cities」,而且我仍然得到了類似的輸出。 SETATTR SFO SJC Anit

+0

我應該改變的變量名呢? – Anit