xml字符串与json互转

首先需要的maven依赖:

<dependency>
   <groupId>org.json</groupId>
   <artifactId>json</artifactId>
   <version>20180813</version>
</dependency>

例子如下:

String xml =
        "\t<root>\n" +
        "\t<QueryCondition>\n" +
        "\t\t<hpzl>02</hpzl>\n" +
        "\t\t<hphm>ll</hphm>\n" +
        "\t\t<dabh></dabh>\n" +
        "\t</QueryCondition>\n" +
        "\t</root>\n";
try {
    org.json.JSONObject xmlJsonObject = XML.toJSONObject(xml);	//实现xml转json
    System.out.println(xmlJsonObject.toString());
    System.out.println(XML.toString(xmlJsonObject));  //实现json转xml字符串
} catch (JSONException e) {
    e.printStackTrace();
}

result is:

{"root":{"QueryCondition":{"hpzl":"02","hphm":"ll","dabh":""}}}
<root><QueryCondition><hpzl>02</hpzl><hphm>ll</hphm><dabh/></QueryCondition></root>

猜你喜欢

转载自blog.csdn.net/genghongsheng/article/details/83056658