Xml 与 Json 文件之间的互转

首先映入依赖:

<dependency> 
	<groupId>net.sf.json-lib</groupId>
	<artifactId>json-lib</artifactId> 
	<version>2.2.2</version>
	<classifier>jdk15</classifier> 
</dependency> 
<!-- xml 文件解析成 json -->
<dependency> 
	<groupId>xom</groupId> 
	<artifactId>xom</artifactId>
	<version>1.2.5</version> 
</dependency>
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.3.1</version>
</dependency>

转换工具:XmlJsonUtil

public class XmlJsonUtil {
    
    

	public static JSONObject xml2json(File file) throws  Exception {
    
    
		FileReader fileReader = new FileReader(file);
		String content = fileReader.readString();
		return xml2json(content);
	}

	public static JSONObject xml2json(String content)  throws  Exception{
    
    
		XMLSerializer xmlSerializer = new XMLSerializer();
		String tempStr = xmlSerializer.read(content).toString();
		JSONObject result = JSONObject.fromObject(tempStr);
		return result;
	}

	public static String json2xml(String json) {
    
    
		JSONObject jsonObject = JSONObject.fromObject(json);
		XMLSerializer xml = new XMLSerializer();
		String xmlStr = xml.write(jsonObject);
		return xmlStr;

	}
}

猜你喜欢

转载自blog.csdn.net/pengain/article/details/112931592