xml字串與json互轉
阿新 • • 發佈:2018-11-20
首先需要的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>