此方法导入org.json的jar包
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;
public class XmlToJson {
public static void main(String[] args) {
String xml = "zhaipuhongmale19701217";
String json = xmlStringToJson(xml);
System.out.println(json);
}
public static String xmlStringToJson(String xmlString) {
//判断字符串是否为空
if(xmlString == null || "".equals(xmlString)){
return "";
}
String json = null;
JSONObject jsonObj = null;
try {
jsonObj = XML.toJSONObject(xmlString);
json = jsonObj.toString(2); //缩进
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
}