How to convert XML to JSON using only Jackson?

后端 未结 6 1810
无人共我
无人共我 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:44

    Using Jackson 2.x

    You can do that with Jackson and no POJOs are required for that:

    String xml = "\n" +
                 "\n" +
                 "  \n" +
                 "    400\n" +
                 "    The field 'quantity' is invalid.\n" +
                 "    
    \n" + " The quantity specified is greater than the quantity of the product that is available to ship.\n" + " 0\n" + " 12525\n" + "
    \n" + "
    \n" + "
    "; XmlMapper xmlMapper = new XmlMapper(); JsonNode node = xmlMapper.readTree(xml.getBytes()); ObjectMapper jsonMapper = new ObjectMapper(); String json = jsonMapper.writeValueAsString(node);

    The following dependencies are required:

    
        com.fasterxml.jackson.core
        jackson-core
        2.8.2
    
    
        com.fasterxml.jackson.core
        jackson-databind
        2.8.2
    
    
        com.fasterxml.jackson.core
        jackson-annotations
        2.8.2
    
    
        com.fasterxml.jackson.dataformat
        jackson-dataformat-xml
        2.8.2
    
    

    Be aware of the XmlMapper limitations stated in the documentation:

    Tree Model is only supported in limited fashion: specifically, Java arrays and Collections can be written, but can not be read, since it is not possible to distinguish Arrays and Objects without additional information.

    Using JSON.org

    You also can do it with JSON.org:

    String xml = "\n" +
                 "\n" +
                 "  \n" +
                 "    400\n" +
                 "    The field 'quantity' is invalid.\n" +
                 "    
    \n" + " The quantity specified is greater than the quantity of the product that is available to ship.\n" + " 0\n" + " 12525\n" + "
    \n" + "
    \n" + "
    "; String json = XML.toJSONObject(xml).toString();

    The following dependency is required:

    
        org.json
        json
        20160810
    
    

提交回复
热议问题