n ways to convert java xml to json

Two methods to convert java xml to json

<?xml version="1.0" encoding="utf-8" ?>
<auibinsurancecallback>
<policyinfo>
<transtype>TKTS</transtype>
<eticketno>xxx</eticketno>
<flightnumber>xxx</flightnumber>
<flightdate>2019-10-16</flightdate>
<operatetime>2019-10-16 17:20:00</operatetime>
<insureno>1910161720056066735</insureno><agreeno>102160199</agreeno>
<policyno>
</policyno><policyurl>
<!--[CDATA[]]-->
</policyurl></policyinfo>
<returninfo>
<serialnumber>2019103015284949545354
</serialnumber>
<retruncode>0</retruncode><errormessage>
<!--[CDATA[xxx]]-->
</errormessage>
</returninfo>
</auibinsurancecallback>";

Let’s look at the effects first, effect one:

{
  "auibinsurancecallback": {
    "returninfo": [
      {
        "retruncode": [
          "0"
        ],
        "serialnumber": [
          "2019103015284949545354"
        ]
      }
    ],
    "policyinfo": [
      {
        "operatetime": [
          "2019-10-16 17:20:00"
        ],
        "transtype": [
          "TKTS"
        ],
        "flightdate": [
          "2019-10-16"
        ],
        "insureno": [
          "1910161720056066735"
        ],
        "flightnumber": [
          "xxx"
        ],
        "agreeno": [
          "102160199"
        ],
        "eticketno": [
          "xxxx"
        ]
      }
    ]
  }
}

Effect two:

{
  "auibinsurancecallback": {
    "returninfo": {
      "errormessage": "",
      "retruncode": 0,
      "serialnumber": 2.0191030152849496e+21
    },
    "policyinfo": {
      "policyurl": "",
      "operatetime": "2019-10-16 17:20:00",
      "transtype": "TKTS",
      "flightdate": "2019-10-16",
      "insureno": 1910161720056066800,
      "flightnumber": "xxx",
      "agreeno": 102160199,
      "policyno": "",
      "eticketno": xxx
    }
  }
}

Judging from the effect, it is obvious that the second method is better than the first.

Post the code below

The first implementation: the packages used are fastjson, jdom2

public static JSONObject xml2JSON(byte[] xml) throws JDOMException, IOException {
        JSONObject json = new JSONObject();
        InputStream is = new ByteArrayInputStream(xml);
        SAXBuilder sb = new SAXBuilder();
        org.jdom2.Document doc = sb.build(is);
        Element root = doc.getRootElement();
        json.put(root.getName(), iterateElement(root));
        return json;
    }
 
    private static JSONObject iterateElement(Element element) {
        List node = element.getChildren();
        Element et = null;
        JSONObject obj = new JSONObject();
        List list = null;
        for (int i = 0; i < node.size(); i++) {
            list = new LinkedList();
            et = (Element) node.get(i);
            if (et.getTextTrim().equals("")) {
                if (et.getChildren().size() == 0)
                    continue;
                if (obj.containsKey(et.getName())) {
                    list = (List) obj.get(et.getName());
                }
                list.add(iterateElement(et));
                obj.put(et.getName(), list);
            } else {
                if (obj.containsKey(et.getName())) {
                    list = (List) obj.get(et.getName());
                }
                list.add(et.getTextTrim());
                obj.put(et.getName(), list);
            }
        }
        return obj;
    }
 
 @Test
    public void xml1(){
        String  xml = 上面贴的xml;
 
        JSONObject json= null;
        try {
            json = xml2JSON(xml.getBytes());
            System.out.println(json.toJSONString());
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
 
    }

The second implementation: using the org.json package,

When using the org.json package, you need to exclude android-json in spring-boot-starter-test, otherwise an error will be reported:

java.lang.NoSuchMethodError: org.json.JSONTokener.<init>(Ljava/io/Reader;)V

java.lang.NoSuchMethodError: org.json.JSONObject.put(Ljava/lang/String;Ljava/util/Collection;)

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>com.vaadin.external.google</groupId>
                    <artifactId>android-json</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

The implementation method is simple:

org.json.JSONObject xmlJSONObj = null;
       try {
           xmlJSONObj = XML.toJSONObject(xml);
           log.debug("json:" + xmlJSONObj.toString() );
       } catch (JSONException e) {
           e.printStackTrace();
       }

This concludes this article on two methods of converting java xml to json.

Guess you like

Origin blog.csdn.net/qq_42003702/article/details/129625524