Xml文件和Json文件对比及相互转化学习记录

用最简单的语言阐述最深刻的知识,纯属个人总结,有所借鉴。

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>

特点

  • 纯文本文件且只有一个根节点(根标签)
  • 所有的标签都需要自定义
  • 所有xml标签都必须有结束标签
  • xml标签对大小写敏感,注意元素命名规则
  • xml标签必须正确嵌套

Json文件(JavaScript Object Notation)

{
	"entity":{
		"user":{
			"password":"666666",
			"id":"1001",
			"age":"16",
			"username":"Logan"
		},
		"order":{
			"date":"2019-02-12",
			"price":"9.99",
			"id":"2001"
		}
	}
}

特点

  • Json对象:在{}中存储键值对,键和值之间用冒号分隔,键值对之间用逗号分隔
  • Json数组:[]中存储多个json对象,json对象之间用逗号分隔

区别

  • 传输同样格式的数据,xml需要使用更多的字符进行描述
  • xml的层次结构比json更清晰

共同点

xml和json都是数据传输的载体,并且具有跨平台跨语言的特性

相互转换

双手奉上工具类

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
 * @version 1.0.0
 * @createDate 2019-02-12
 */
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 class XmlJsonTest {
    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, "C:\\Users\\user\\Desktop\\User.xml");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

pom依赖

<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>

通过以上代码可以完美实现xml与json的互相转换

 

未完待续...

后期继续补充Json数组转Xml的方式

参考原文https://blog.csdn.net/cao1315020626/article/details/90303721

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值