JSON对象与XML相互转换工具类
依赖jar
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency> <dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
JsonXmlUtils.java
package javax.utils; import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.nio.file.Paths; import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.xml.sax.SAXException; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; /**
* JSON对象与XML相互转换工具类
*
* @author Logan
* @createDate 2019-02-12
* @version 1.0.0
*
*/
public class JsonXmlUtils { private static final String ENCODING = "UTF-8"; /**
* JSON对象转漂亮的xml字符串
*
* @param json JSON对象
* @return 漂亮的xml字符串
* @throws IOException
* @throws SAXException
*/
public static String jsonToPrettyXml(JSONObject json) throws IOException, SAXException {
Document document = jsonToDocument(json); /* 格式化xml */
OutputFormat format = OutputFormat.createPrettyPrint(); // 设置缩进为4个空格
format.setIndent(" ");
format.setIndentSize(4); StringWriter formatXml = new StringWriter();
XMLWriter writer = new XMLWriter(formatXml, format);
writer.write(document); return formatXml.toString();
} /**
* JSON对象转xml字符串
*
* @param json JSON对象
* @return xml字符串
* @throws SAXException
*/
public static String JsonToXml(JSONObject json) throws SAXException {
return jsonToDocument(json).asXML();
} /**
* JSON对象转Document对象
*
* @param json JSON对象
* @return Document对象
* @throws SAXException
*/
public static Document jsonToDocument(JSONObject json) throws SAXException {
Document document = DocumentHelper.createDocument();
document.setXMLEncoding(ENCODING); // root对象只能有一个
for (String rootKey : json.keySet()) {
Element root = jsonToElement(json.getJSONObject(rootKey), rootKey);
document.add(root);
break;
}
return document;
} /**
* JSON对象转Element对象
*
* @param json JSON对象
* @param nodeName 节点名称
* @return Element对象
*/
public static Element jsonToElement(JSONObject json, String nodeName) {
Element node = DocumentHelper.createElement(nodeName);
for (String key : json.keySet()) {
Object child = json.get(key);
if (child instanceof JSONObject) {
node.add(jsonToElement(json.getJSONObject(key), key));
} else {
Element element = DocumentHelper.createElement(key);
element.setText(json.getString(key));
node.add(element);
}
} return node;
} /**
* XML字符串转JSON对象
*
* @param xml xml字符串
* @return JSON对象
* @throws DocumentException
*/
public static JSONObject xmlToJson(String xml) throws DocumentException {
JSONObject json = new JSONObject(); SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(xml));
Element root = document.getRootElement(); json.put(root.getName(), elementToJson(root)); return json;
} /**
* Element对象转JSON对象
*
* @param element Element对象
* @return JSON对象
*/
public static JSONObject elementToJson(Element element) {
JSONObject json = new JSONObject();
for (Object child : element.elements()) {
Element e = (Element) child;
if (e.elements().isEmpty()) {
json.put(e.getName(), e.getText());
} else {
json.put(e.getName(), elementToJson(e));
}
} return json;
} /**
* 文件内容转换成字符串
*
* @param filePath 文件路径
* @return 内容字符串
* @throws IOException
*/
public static String fileToString(URL filePath) throws IOException {
return IOUtils.toString(filePath, ENCODING);
} /**
* 文件内容转换成字符串
*
* @param filePath 文件路径
* @return 内容字符串
* @throws IOException
*/
public static String fileToString(String filePath) throws IOException {
return IOUtils.toString(Paths.get(filePath).toUri(), ENCODING);
} /**
* 字符串输出到文件
*
* @param str 字符串内容
* @param filePath 文件路径
* @throws IOException
*/
public static void stringToFile(String str, String filePath) throws IOException {
FileUtils.writeStringToFile(Paths.get(filePath).toFile(), str, ENCODING);
} /**
* 字符串输出到文件
*
* @param str 字符串内容
* @param filePath 文件路径
* @throws IOException
*/
public static void stringToFile(String str, URL filePath) throws IOException {
FileUtils.writeStringToFile(new File(filePath.getPath()), str, ENCODING);
} /**
* 字符串输出到文件
*
* @param str 字符串内容
* @param file 输出文件
* @throws IOException
*/
public static void stringToFile(String str, File file) throws IOException {
FileUtils.writeStringToFile(file, str, ENCODING);
} public static void main(String[] args) {
try {
String filePath = "/User.xml";
URL url = JsonXmlUtils.class.getResource(filePath);
String content = JsonXmlUtils.fileToString(url);
// System.out.println(content); JSONObject json = xmlToJson(content);
System.out.println(JSON.toJSONString(json, true)); String xml = JsonToXml(json);
System.out.println(xml); System.out.println("----------------------------------------\n\n");
xml = jsonToPrettyXml(json);
System.out.println(xml); stringToFile(xml, "G:\\Temp\\Test\\User.xml");
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
} }
测试文件
User.xml
<?xml version="1.0" encoding="UTF-8"?>
<entity>
<user>
<id>1001</id>
<username>Logan</username>
<password>666666</password>
<age>16</age>
</user>
<order>
<id>2001</id>
<price>9.99</price>
<date>2019-02-12</date>
</order>
</entity>
.
JSON对象与XML相互转换工具类的更多相关文章
- java对象与xml相互转换工具类
public class XmlHelper { /** * Object转XML * * @param object * @return * @throws Exception */ public ...
- java对象与xml相互转换 ---- xstream
XStream是一个Java对象和XML相互转换的工具,很好很强大.提供了所有的基础类型.数组.集合等类型直接转换的支持. XStream中的核心类就是XStream类,一般来说,熟悉这个类基本就够用 ...
- .NET3.5中JSON用法以及封装JsonUtils工具类
.NET3.5中JSON用法以及封装JsonUtils工具类 我们讲到JSON的简单使用,现在我们来研究如何进行封装微软提供的JSON基类,达到更加方便.简单.强大且重用性高的效果. 首先创建一个类 ...
- json对象与string相互转换教程
一.说明 1.1 背景说明 json对象与string相互转换,这东西想写了很多次,但总觉得网上教程比较成熟,所以之前每次都放弃了.但今天又被string转json对象折腾了半天,实在受不了,所以还是 ...
- Map 集合 和 String 字符串相互转换工具类
package com.skynet.rimp.common.utils.util; import java.util.Arrays; import java.util.HashMap; import ...
- 阶段3 1.Mybatis_03.自定义Mybatis框架_4.自定义mybatis的编码-解析XML的工具类介绍
导入xml操作的类和用到的相关包 创建util包,然后把提供好的XMLConfigBuilder.java文件复制3过来 复制过来,里面用到了很多dom4j的东西 打开pom.xml 输入depend ...
- XML读写工具类
摘要:①读取XML文件,生成pojo对象:②将对象信息保存到xml中. 步骤: ①新建一个普通的java类BasePage: package com.test.selenium.pages; impo ...
- 玩转Java对象和XML相互转换
最近在项目中一直出现Java对象和XML之间的相互转换,一开始由于项目很庞大,我又是临时调度过去,导致在按照项目组长的要求进行写代码的同时,总是在这块云里雾里,最近才慢慢开始搞清楚项目中具体的使用缘由 ...
- 在spring中获取代理对象代理的目标对象工具类
昨天晚上一哥们需要获取代理对象的目标对象,查找了文档发现没有相应的工具类,因此自己写了一个分享给大家.能获取JDK动态代理/CGLIB代理对象代理的目标对象. 问题描述:: 我现在遇到个棘手的问题,要 ...
随机推荐
- my05_mysql检查点简述
简单描述一下mysql 检查点,对mysql数据库恢复的理解有所帮助. 数据库版本 mysql> select version(); +-----------+ | version() | +- ...
- java——斗地主小游戏之洗牌发牌
遇到的问题: 1.int和Integer的区别? 1)Integer是int的包装类,int则是java的一种基本数据类型 . 2)Integer变量必须实例化后才能使用,而int变量不需要 . 3) ...
- 未来HTML6出现的10个特性
网络技术正趋向于发展为一个巨大的移动APP市场,在Web开发的革命浪潮中起着指示性作用,自HTML引入以来,创建可转换,有新意的网络移动应用程序变得So easy,web开发中运用先进技术也很容易处理 ...
- 用python处理时间、utf8文本、正则匹配、序列化、目录路径搜索、xml解析
python 处理时间 import time import re now = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) ...
- 【3dsMax安装失败,如何卸载、安装3dMax 2017?】
是不是遇到MAYA/CAD/3DSMAX/INVENTOR安装失败?AUTODESK系列软件着实令人头疼,MAYA/CAD/3DSMAX/INVENTOR安装失败之后不能完全卸载!!!(比如maya, ...
- IDEA部署Express工程
1.下载并安装Nodejs 2.通过Nodejs的NPM工具安装全局安装express工具,命令如下: npm install -g express@XXX npm install -g expres ...
- 【密码学】CSP的概念
CSP加密服务提供者(Cryptographic Service Provider)具有一下几个特点: CSP是真正执行密码运算的独立模块 物理上一个CSP由两部分组成:一个动态连接库,一个签名文件 ...
- Oracle安装后忘记用户名或密码+创建新登陆用户
新安装的Oracle11g,不料在使用的时候没记住安装时的用户名和密码. 不用担心,打开sqlplus. 按如下步骤,新建一个登陆用户: 第一步:以sys登陆 sys/密码 as sysdba 此 ...
- 【转】Android Canvas绘图详解
转自:http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2012/1212/703.html Android中使用图形处理引擎,2D部分是an ...
- phpstorm 配置 webserver ,配置根目录
原文链接 http://blog.csdn.net/pony_maggie/article/details/52367093 phpstorm自带了一个web server,我们可以直接在IDE ...