如何在java中将复杂的XML转换为JSON? [重复]

时间:2021-09-07 23:44:40

This question already has an answer here:

这个问题在这里已有答案:

I have an XML where the structure looks as below. It is a complex XML where we have multiple attributes. How to convert this XML to JSON using java. Please suggest.

我有一个XML,其结构如下所示。它是一个复杂的XML,我们有多个属性。如何使用java将此XML转换为JSON。请建议。

The input looks something like below.

输入看起来如下所示。

input

输入

<?XML version="1.0" encoding="UTE-8"?>
        <Products>
            <Product>
                <List>
                    <Property name="description" value="Skype"/>
                </List>
            </Product>
        </Products>

Expected Output is

预期产出是

 {
       "Products": {
          "Product": {
             List": [
                {
                   "description": "Skype"
                }
             ]
          }
       }
    } 

1 个解决方案

#1


0  

You can achieve with the JSON Api with something like below

你可以用下面的东西来实现JSON Api

import org.json.JSONObject;
import org.json.XML;
import org.junit.Test;

And then in the code use below way:

然后在代码中使用以下方式:

JSONObject xmlJSONObj = XML.toJSONObject(XML_TEXT);
        String jsonString = xmlJSONObj.toString();
        System.out.println(jsonString );

#1


0  

You can achieve with the JSON Api with something like below

你可以用下面的东西来实现JSON Api

import org.json.JSONObject;
import org.json.XML;
import org.junit.Test;

And then in the code use below way:

然后在代码中使用以下方式:

JSONObject xmlJSONObj = XML.toJSONObject(XML_TEXT);
        String jsonString = xmlJSONObj.toString();
        System.out.println(jsonString );