This article will introduce two methods of converting json to xml. I hope it will be helpful to everyone.
The first method
Use the XML.toJSONObject(xml) method provided in XML.java to complete the xml to json conversion, you can also format JSON
/* 第一种方法,使用JSON-JAVA提供的方法 */ //将xml转为json JSONObject xmlJSONObj = XML.toJSONObject(xml); //设置缩进 String jsonPrettyPrintString = xmlJSONObj.toString(4); //输出格式化后的json System.out.println(jsonPrettyPrintString);
Second method
Use the XMLSerializer object of json-lib
/* 第二种方法,使用json-lib提供的方法 */ //创建 XMLSerializer对象 XMLSerializer xmlSerializer = new XMLSerializer(); //将xml转为json(注:如果是元素的属性,会在json里的key前加一个@标识) String result = xmlSerializer.read(xml).toString(); //输出json内容 System.out.println(result);
Note:When converting xml to json through json-lib, empty nodes will be converted into empty arrays, that is, [], which is very bad, so you need to convert [] into an empty string: jsonStr. replace("[]", "\"\"")
Related learning recommendations: java basics
The above is the detailed content of What to use to convert json to xml. For more information, please follow other related articles on the PHP Chinese website!