Format and parsing of XML and JSON

Posted by caspert_ghost on Tue, 14 Dec 2021 20:55:32 +0100

1.XML

This is an example of xml format:

<?xml version="1.0" encoding="UTF-8"?>
<books>
    <book id="1001">
        <name>book1</name>
        <info>This is the introduction of the first book!</info>
    </book>
    <book id="1002">
        <name>book2</name>
        <info>This is the introduction of the second book!</info>
    </book>
</books>

XML can be used to:

  1. Network data transmission ❌ (JSON is basically used now)

    JSON parsing performance is higher than XML, and the larger the amount of data, the more obvious the gap is, but XML is more readable. XML is mainly used to write configuration files.

  2. data storage ❌ (basically not used)

  3. Configuration files (XML is mainly used for configuration files)

    XML focuses on mastering the syntax format and parsing XML.

How to parse XML:

  1. SAX parsing does not need to load all documents into memory, which takes up very little memory. One way parsing requires programmers to maintain the parent-child relationship of nodes.
  2. DOM parsing: loading the whole document into memory and establishing a tree model consumes a lot of resources (the disadvantages are negligible) and is convenient to operate data and structures. DOM parsing is usually used.

Here are two examples of parsing xml:

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * dom4j dom Parsing network xml example
 * This api is used to parse and query the mobile phone number attribution
 * api:
 * http://apis.juhe.cn/mobile/get?phone="+phone+"&dtype=xml&key=9f3923e8f87f1ea50ed4ec8c39cc9253"
 * */
public class XmlTest {
    public static void main(String[] args) throws IOException, DocumentException {
        String phone = "18159895016";
        URL url = new URL("http://apis.juhe.cn/mobile/get?phone="+phone+"&dtype=xml&key=9f3923e8f87f1ea50ed4ec8c39cc9253");
        //Open this url to get a connection
        URLConnection urlConnection = url.openConnection();
        //Gets the input stream of the connection
        InputStream is = urlConnection.getInputStream();
        SAXReader saxReader = new SAXReader();
        //Convert input to doc
        Document doc = saxReader.read(is);
        //Get root node
        Element root = doc.getRootElement();
        String resultcode = root.elementText("resultcode");
        if ("200".equals(resultcode)){
            Element result = root.element("result");
            String province = result.elementText("province");
            String city = result.elementText("city");
            String company = result.elementText("company");
            if (city.equals(province)){
                System.out.println("The mobile phone number belongs to:"+city);
            }else {
                System.out.println("The mobile phone number belongs to:"+province+" "+city);
            }
            System.out.println("The mobile number operator is:"+company);

        }else {
            System.out.println("Wrong mobile phone number! Parsing error!");
        }
    }
}
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * dom4j  XPATH Parsing network xml
 * XPATH Very convenient, especially when xml is large
 *
 * This api is used to parse and query the mobile phone number attribution
 * api:
 * http://apis.juhe.cn/mobile/get?phone="+phone+"&dtype=xml&key=9f3923e8f87f1ea50ed4ec8c39cc9253"
 * */
public class XpathTest {
    public static void main(String[] args) throws IOException, DocumentException {
        String phone = "18159895016";
        URL url = new URL("http://apis.juhe.cn/mobile/get?phone="+phone+"&dtype=xml&key=9f3923e8f87f1ea50ed4ec8c39cc9253");
        URLConnection urlConnection = url.openConnection();
        InputStream is = urlConnection.getInputStream();
        SAXReader saxReader = new SAXReader();
        Document doc = saxReader.read(is);
        //Obtain the single node company. As a demonstration, only the operator is obtained here, and the rest of the information is not obtained
        Node node = doc.selectSingleNode("//company");
        System.out.println(node.getName()+":"+node.getText());
    }
}

In addition, both Jdom and dom4j are based on dom.

jdom is convenient for java development, and its performance is not very high, and it is not flexible enough (because it is written for classes)

dom4j has higher performance and flexibility (because it is written for interface), and can be parsed by XPATH.

Dom4j is an excellent open source java xml api with excellent performance, powerful functions and easy to use.

Many open source projects use Dom4j to read and write xml, such as Hibernate

2.JSON

JSON is a lightweight data exchange format.

JS ON (JavaScript Object Notation) is a language independent data storage format and a specification in JavaScript proposed in Europe.

Parsing: parsing json is faster than parsing xml,

In terms of data storage: the data represented by json takes up less space and is more conducive to transmission.

json appeared in 1999. Thanks to the above advantages, it gradually replaced xml around 2005.

Storage object format comparison:

Json is used very frequently, and it is often used in back-end development.

Java has no built-in class for parsing Json. The most commonly used methods for parsing Json are:

  1. Gson: Google's
  2. Fastjason: Ali's
//For the use of Gson and fastjason, if the attribute in json is array type, it will be resolved to List type
public class JsonTest {
    public static void main(String[] args) {
        Person p = new Person("Zhang San",20,"Daxing District ");
/*        Gson g = new Gson();
        //Convert object to json
        String s = g.toJson(p);
        System.out.println("Converting an object to json is: ");
        System.out.println(s);
        //Convert json to object
        Person p2 = g.fromJson(s, Person.class);
        System.out.println("Converting json to an object is: ");
        System.out.println(p2);*/
        
        //Ali's fastjson
        String s = JSON.toJSONString(p);
        System.out.println(s);
        Person p2 = JSON.parseObject(s,Person.class);
        System.out.println(p2);
    }
}

Topics: Java JSON xml