Convert xml to json with Java

2020-02-04 21:06发布

Is there a way to convert a xml file to json? The XML can be of any structure, therefore there is no POJO class for instantiation. I need to convert the xml to json or to a Map, without root nodes.

For example:

<import name="person">
    <item>
        <firstName>Emil</firstName>
        <lastName>Example</lastName>
        <addresses>
            <address>
                <street>Example Blvd.</street>
            </address>
            <address>
                <street>Example Ave.</street>
            </address>
        </addresses>
    </item>
</import>

Expected JSON

{
    "firstName": "Emil",
    "lastName": "Example",
    "addresses": [
        { "street" : "Example Blvd." },
        { "street" : "Example Ave." }
    ]
}

标签: java xml json
7条回答
地球回转人心会变
2楼-- · 2020-02-04 21:37

I am used JSON-java but I found more Efficient Library to Convert XML to Json is XmlToJson

Which is Given Best Customization to making Json fromXML

Add the libary dependency to your APP build.gradle file

dependencies {
compile 'com.github.smart-fun:XmlToJson:1.4.4'    // add this line
}

    <?xml version="1.0" encoding="utf-8"?>
    <library>
    <book id="007">James Bond</book>
    <book id="000">Book for the dummies</book>
    </library>
  • Custom Content names

    public String convertXmlToJson(String xml) {
    XmlToJson xmlToJson = new XmlToJson.Builder(xml)
        .setContentName("/library/book", "title")
        .build();
    return xmlToJson.toString();
    }
    

    "library":{  
      "book":[  
         {  
            "id":"007",
            "title":"James Bond"
         },
         {  
            "id":"000",
            "title":"Book for the dummies"
         }
       ]
      }
     }
    

  • Custom Attributes names

    public String convertXmlToJson(String xml) {
      XmlToJson xmlToJson = new XmlToJson.Builder(xml)
        .setAttributeName("/library/book/id", "code")
        .build();
      return xmlToJson.toString();
    }
    

    {  
      "library":{  
      "book":[  
         {  
            "code":"007",
            "content":"James Bond"
         },
         {  
            "code":"000",
            "content":"Book for the dummies"
         }
      ]
     }
    }
    

and Much More Efficient Techniques to Customize your Json

Click here to Check out on Github

查看更多
登录 后发表回答