简体   繁体   中英

Map Jackson json attribute to corresponding xml element

I am using Jackson objectMapper to read JSON to JsonNode, Then I am using xmlMapper to serialize this to XML.

I'd like to set an XML attribute value by parsing a JSON attribute with tag "@". Any help would be appreciated. Thanks.

EXAMPLE JSON:

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

NEED TO MAP TO XML:

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

This is what I can get right now:

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

CODE:

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

well, I found a solution that produces the required output. However, I am not sure if this is an optimal solution, in a sense that it requires custom inner classes to be able to specify the annotations that tell the mappers how to parse.

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

output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM