Home > Java > javaTutorial > What to use to convert json to xml

What to use to convert json to xml

(*-*)浩
Release: 2020-09-19 14:55:26
Original
6448 people have browsed it

This article will introduce two methods of converting json to xml. I hope it will be helpful to everyone.

What to use to convert json to xml

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);
Copy after login

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);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template