首先要去官方下载json-lib工具包
https://mvnrepository.com/artifact/net.sf.json-lib/json-lib/2.4
目前最新的是2.4的版本,json-lib还需要以下依赖包:
通过mvn库可以直接去下载。
jakartacommons-lang 2.5
jakartacommons-beanutils 1.8.0
jakartacommons-collections 3.2.1
jakartacommons-logging 1.1.1
ezmorph1.0.6
From JSON to XML
Code | XML output |
1. JSONObject json = new JSONObject( true ); 2. String xml = XMLSerializer.write( json ); | 1. <o class="object" null="true"> 2. |
1. JSONObject json = JSONObject.fromObject("{\"name\":\"json\",\"bool\":true,\"int\":1}"); 2. String xml = XMLSerializer.write( json ); |
JSONArray json = JSONArray.fromObject("[1,2,3]");
String xml = XMLSerializer.write( json );
From XML to JSON
Code | |
1. <a class="array"> 2. <e type="function" params="i,j"> 3. return matrix[i][j]; 4. </e> 5. </a> | 1. JSONArray json = (JSONArray) XMLSerializer.read( xml ); 2. System.out.println( json ); 3. // prints [function(i,j){ return matrix[i][j]; }] |
自己示例:
public String segmentXml(String text) {
JSONObject jsonObjec =segmentJson(text);
String xml = json2XML(jsonObjec.toString());
return xml;
}