How to convert XML to JSON using only Jackson?

后端 未结 6 1803
无人共我
无人共我 2020-11-30 04:35

I am getting a response from server as XML. But I need to display this in JSON format.

Is there any way to convert it without any third party API? I used Jackson but

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-30 04:56

    I know that I am too late for an answer here. But I am writing this for the new guys who stumbled upon this question and thinking to use @Cassio's answer.

    The problem of using XmlMpper to de-serialize to a JsonNode is that, when there are multiple elements with the same name at the same level, then it will replace the previous one with the new one and end up with data loss. Usually, we've to add this to an array. To tackle this problem, we can override the _handleDuplicateField() method of the JsonNodeDeserializer class. Enough talking. Let's see the code

    public class DuplicateToArrayJsonNodeDeserializer extends JsonNodeDeserializer {
    
        @Override
        protected void _handleDuplicateField(JsonParser p, DeserializationContext ctxt, 
            JsonNodeFactory nodeFactory,String fieldName, ObjectNode objectNode,
            JsonNode oldValue, JsonNode newValue) throws JsonProcessingException {
            ArrayNode node;
            if(oldValue instanceof ArrayNode){
                node = (ArrayNode) oldValue;
                node.add(newValue);
            } else {
                node = nodeFactory.arrayNode();
                node.add(oldValue);
                node.add(newValue);
            }
            objectNode.set(fieldName, node);
        }
    }
    

    Since we've overridden the default deserializer, we also need to register this in the XmlMapper to make it work.

    XmlMapper xmlMapper = new XmlMapper();
    xmlMapper.registerModule(new SimpleModule().addDeserializer(
        JsonNode.class, 
        new DuplicateToArrayJsonNodeDeserializer()
    ));
    JsonNode node = xmlMapper.readTree(payLoad);
    

提交回复
热议问题