簡體   English   中英

將Jackson json屬性映射到相應的xml元素

[英]Map Jackson json attribute to corresponding xml element

我使用Jackson objectMapper將JSON讀取到JsonNode,然后我使用xmlMapper將其序列化為XML。

我想通過解析帶有標記“@”的JSON屬性來設置XML屬性值。 任何幫助,將不勝感激。 謝謝。

示例JSON:

{
  "response" : {
    "label" : {
      "@data" : "someValue"
    }
  }
}

需要映射到XML:

<response>
  <label data="someValue" />
</response>

這就是我現在能得到的:

<response>
  <label>
     <@data>someValue</@data>
  </label>
</response>

碼:

JsonNode root = objectMapper.readTree(JSON); 
xml = xmlMapper.writeValueAsString(root);

好吧,我找到了一個產生所需輸出的解決方案。 但是,我不確定這是否是一個最佳解決方案,從某種意義上說,它需要自定義內部類來指定告訴映射器如何解析的注釋。

import java.util.*;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;

public class JSONTest
{
    @SuppressWarnings("unchecked")
    public static void main(String[] args)
    {
        try {
            String jsonInput = "{  \"response\" : {    \"label\" : {      \"@data\" : \"someValue\"    }  }}";

            ObjectMapper om = new ObjectMapper();
            TypeFactory tf = om.getTypeFactory();
            JavaType mapType = tf.constructMapType(HashMap.class, String.class, response.class);
            Map<String, response> map = (Map<String, response>)om.readValue(jsonInput, mapType);

            XmlMapper xmlMapper = new XmlMapper();
            String ss = xmlMapper.writeValueAsString(map.get("response"));
            System.out.println(ss);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static class response {
        public Label label;
    }

    public static class Label {
        @JsonProperty("@data")
        @JacksonXmlProperty(isAttribute = true)
        public String data;
    }
}

輸出:

<response><label data="someValue"/></response>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM