一文帮你完美解决Json和Xml相互转换
json
适用于现代 C++ 的 JSON。
项目地址:https://gitcode.com/gh_mirrors/js/json
免费下载资源
·
目录
我们经常会碰到Json和Xml相互转换,但是转换过程中经常出现各种奇葩问题,比如多节点了或少节点了,或者转换后的格式不对,多了空数组,还有就是遇到带属性的xml格式转换完之后属性没了等等,今天就手把手教你完美解决这些坑。上代码
1、导入用到的jar包
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<!-- 加入jdk15,不然jar包下载不下来 -->
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>xom</groupId>
<artifactId>xom</artifactId>
<version>1.2.5</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- json 转xml用 -->
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.0.0</version>
</dependency>
2.1、xml格式转换为json格式
会丢失节点,如以下列子会丢student节点,但是如果xml存在属性节点,该方法不会丢失,会转换为@+属性名称
public static void main(String[] args) {
String dest="";
String result="<?xml version="1.0" encoding="UTF-8"?><class><name>实验1班</name><no>2020</no><students><student><name>张三</name><sex>女</sex></student><student><name>李四</name><sex>男</sex></student></students></class>
" ;
if (result != null) {
Pattern p = Pattern.compile("\\s{3,}|\t|\r|\n");//去掉多余的空格(跳过开头<?xml version="1.0" encoding="UTF-8"/>中的空格)
Matcher m = p.matcher(result);
dest = m.replaceAll("");
System.out.println(dest);
}
//将xml转为json(注:如果是元素的属性,会在json里的key前加一个@标识)
XMLSerializer xmlSerializer = new XMLSerializer();
//将输出的[]转换为""
String json = xmlSerializer.read(dest).toString().replace("[]", "\"\"");
System.out.println(json);
//{"name":"实验1班","no":"2020","students":[{"name":"张三","sex":"女"},{"name":"李四","sex":"男"}]}
}
最终的结果为
{
"name": "实验1班",
"no": "2020",
"students": [
{
"name": "张三",
"sex": "女"
},
{
"name": "李四",
"sex": "男"
}
]
}
2.2 xml 转json格式(不会丢失节点)
该方法是先将xml转换为map,再转为json,但是该方法会丢失xml的属性节点。
import net.sf.json.JSONObject;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class XmlToJson {
public static void main(String[] args) {
String dest="";
String xmlStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?><class><name>实验1班</name><no>2020</no><students><student><name>张三</name><sex>女</sex></student><student><name>李四</name><sex>男</sex></student></students></class>" ;
if (!"".equals(xmlStr)) {
Pattern p = Pattern.compile("\\s{3,}|\t|\r|\n");//去掉多余的空格和换行(跳过开头<?xml version="1.0" encoding="UTF-8"/>中的空格)
Matcher m = p.matcher(xmlStr);
dest = m.replaceAll("");
}
Map<String, Object> stringObjectMap = Xml2Map(dest);
JSONObject jsonObject = (JSONObject) JSONObject.fromObject(stringObjectMap);
System.out.println(jsonObject);
//{"no":"2020","name":"实验1班","students":{"student":[{"sex":"女","name":"张三"},{"sex":"男","name":"李四"}]}}
}
public static Map<String, Object> Xml2Map(String result) {
Document doc = null;
try {
doc = DocumentHelper.parseText(result);
} catch (DocumentException e) {
e.printStackTrace();
}
Map<String, Object> map = new HashMap<String, Object>();
if (result == null) {
return map;
}
Element root = doc.getRootElement();
for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {
Element e = (Element) iterator.next();
List list = e.elements();
if (list.size() > 0) {
map.put(e.getName(), Element2Map(e));
} else
map.put(e.getName(), e.getText());
}
return map;
}
public static Map Element2Map(Element e) {
Map map = new HashMap();
List list = e.elements();
if (list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
Element iter = (Element) list.get(i);
List mapList = new ArrayList();
if (iter.elements().size() > 0) {
Map m = Element2Map(iter);
if (map.get(iter.getName()) != null) {
Object obj = map.get(iter.getName());
if (!obj.getClass().getName()
.equals("java.util.ArrayList")) {
mapList = new ArrayList();
mapList.add(obj);
mapList.add(m);
}
if (obj.getClass().getName()
.equals("java.util.ArrayList")) {
mapList = (List) obj;
mapList.add(m);
}
map.put(iter.getName(), mapList);
} else
map.put(iter.getName(), m);
} else {
if (map.get(iter.getName()) != null) {
Object obj = map.get(iter.getName());
if (!obj.getClass().getName().equals("java.util.ArrayList")) {
mapList = new ArrayList();
mapList.add(obj);
mapList.add(iter.getText());
}
if (obj.getClass().getName().equals("java.util.ArrayList")) {
mapList = (List) obj;
mapList.add(iter.getText());
}
map.put(iter.getName(), mapList);
} else
map.put(iter.getName(), iter.getText());
}
}
} else
map.put(e.getName(), e.getText());
return map;
}
}
转换结果符合要求,没有丢失节点
{
"no": "2020",
"name": "实验1班",
"students": {
"student": [
{
"sex": "女",
"name": "张三"
},
{
"sex": "男",
"name": "李四"
}
]
}
}
3、json格式转换为xml格式
假设我们要把刚才转出的json转换为xml
public static void main(String[] args) {
String jsonStr = "{"name":"实验1班","no":"2020","students":[{"name":"张三","sex":"女"},{"name":"李四","sex":"男"}]}";
String xmlStr = json2XmlString(jsonStr,"class");
System.out.println(xmlStr);
//<?xml version="1.0" encoding="utf-8"?><class><name>实验1班</name><no>2020</no><students><name>张三</name><sex>女</sex><name>李四</name><sex>男</sex></students></class>
}
/**
*
* @param jsonStr json字符串
* @param rootName xml 最外层节点名称,如<class></class>
* @return
*/
public static String json2XmlString(String jsonStr,String rootName){
StringBuffer sb = new StringBuffer();
String xmlStr = "";
JSONObject json = JSONObject.fromObject(jsonStr);
XMLSerializer xmlSerializer = new XMLSerializer();
xmlSerializer.setRootName(rootName);
xmlSerializer.setTypeHintsEnabled(false);
String xml = xmlSerializer.write(json);
xml = xml.replace("<o>", "").replace("</o>", "");
xml = xml.replace("<e>", "").replace("</e>", "");
xml = xml.replaceAll("\r\n", "").concat("\r\n");
Document document;
try {
document = DocumentHelper.parseText(xml);
xmlStr = document.getRootElement().asXML();
} catch (DocumentException e) {
e.printStackTrace();
}
sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>")
.append(xmlStr);
return sb.toString();
}
有问题欢迎加群讨论:700637673
GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:1 个月前 )
960b763e
4 个月前
8c391e04
6 个月前
更多推荐
已为社区贡献5条内容
所有评论(0)