2014-01-13 2 views
4

POJO 또는 JSON을 올바른 위치에있는 모든 속성을 사용하여 XML로 변환하는 가장 좋은 방법을 찾고 있습니다. 지금은 잭슨이 가장 편리한 방법처럼 보입니다. 속성없이 XML에 POJO를 직렬화 할 수 있습니다.POJO를 Jackson과 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 결과는 내가 @JacksonXmlProperty를 사용하여 몇 가지 예를 발견이

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

처럼 보이지만 그것은 단지 루트 요소에 속성을 추가합니다.

도움을 주셔서 감사합니다.

+0

'TestUser'에서 확장하고있는'JsonType'의 완전한 패키지 이름은 무엇입니까? – Chaitanya

답변

1

흥미로운 문제 : 추가 데이터를 주입합니다. 현재이 작업을 수행 할 수있는 기능은 없습니다. 그러나 나는 @JsonRootName (schema=URL?)에 새로운 속성을 추가하는 것이 가능하다고 생각합니다. 그러면 스키마 매핑이나 매핑을 추가 할 수 있습니까?

내가 나서서이 제기 :

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

작동합니다 뭔가를 추가하는 방법을; 의견, 제안을 자유롭게 추가하십시오.

관련 문제