2014-01-13 82 views
4

我正在尋找最佳解決方案,如何將POJO或JSON轉換爲XML,並使用正確位置的所有atttribute。就目前而言,傑克遜看起來是最方便的方式。我能夠將POJO序列化爲不帶屬性的XML。如何使用Jackson將POJO轉換爲XML

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

下面是代碼:

public void testJsonToXML() throws JsonParseException, JsonMappingException, IOException 
{ 
    String jsonInput = "{\"username\":\"FOO\",\"fullname\":\"FOO BAR\", \"email\":\"[email protected]\", \"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>[email protected]</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>[email protected]</email> 
    </product> 
</TestUser> 

我發現使用@JacksonXmlProperty一些例子,但它只會增加該屬性的根元素。

感謝您的幫助

+0

您在'TestUser'中擴展的'JsonType'的完整軟件包名稱是什麼? – Chaitanya

回答

1

有趣的問題:注入額外的數據。目前沒有這樣做的功能;但我認爲可以在@JsonRootNameschema=URL?)中添加新的屬性,這將允許添加模式映射或映射?

我繼續申請此:

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

添加的東西,應該工作;隨時添加評論,建議。

相關問題