Java learning notes XML and JSON

XML and JSON

1, XML(eXtensible Markup Language)

  • characteristic:

    1. xml is a platform independent markup language

    2. xml is self descriptive

  • effect:

    1. Network data transmission
    2. data storage
    3. configuration file
  • xml file: xml file is a way to save xml data

  • xml syntax (see a case)

<?xml version="1.0" encoding="UTF-8"?> 
<!--First line statement xml Version and character encoding-->
<!--Tags can be nested. The first layer is the root tag, and the tags of the same layer are juxtaposed-->
<books>
    <book id="101">
    	<name>Journey to the West</name>
        <info>Monk Tang and three disciples went to the west to learn scriptures</info>
    </book>
    <book id="102">
    	<name>Water Margin</name>
        <info>Heroic stories of 108 heroes in Liangshan in the late Northern Song Dynasty</info>
    </book>
</books>
  • xml parsing

    1. SAX analysis: event driven mechanism; Read the XML file line by line, and trigger the event when parsing to the start / end / content / attribute of a tag.

      • advantage:

        1. Analysis can start immediately, rather than waiting for all data to be processed

        2. Load line by line to save memory and help parse documents larger than system memory

        3. Sometimes you don't have to parse the entire document. You can stop parsing when you finish the task.

      • Disadvantages:

        1. One way parsing, unable to locate the document hierarchy, unable to access the data of different parts of the same document at the same time (no memory, no backtracking)

        2. You cannot know the hierarchy of the element when the event occurs. You can only maintain the parent-child relationship of the node yourself

        3. Read only parsing mode, unable to modify the content of xml document

    2. DOM parsing: the official W3C standard for representing XML documents in a platform and language independent manner. Analyzing this structure usually requires loading the whole document and establishing a document tree model in memory. Programmers can complete data acquisition, modification, deletion, etc. by operating the document tree.

      • advantage

        The document is loaded in memory, allowing changes to the data and structure tree

        The access is bidirectional, and the data can be parsed Bi directionally in the tree at any time

      • shortcoming

        All documents are loaded in memory, which consumes a lot of resources

    3. JDOM: simplify the interaction with XML and realize faster using dom. It is the first Java specific model, which simplifies the API of DOM and uses a large number of collection classes to facilitate Java developers.

    4. DOM4J: an intelligent branch of JDOM, supporting XPath.

  • XML parsing case

    1. Parse from local file

      package day29;
      
      import org.dom4j.Document;
      import org.dom4j.DocumentException;
      import org.dom4j.Element;
      import org.dom4j.io.SAXReader;
      
      import java.io.FileInputStream;
      import java.io.IOException;
      import java.util.List;
      
      public class Demo {
          public static void main(String[] args) throws IOException, DocumentException {
              //Read the file and get the input stream
              FileInputStream fis = new FileInputStream("C:\\Users\\Administrator\\IdeaProjects\\Practice\\src\\day29\\Demo.xml");
              //Create resolution method
              SAXReader sr = new SAXReader();
              //After parsing the file with SAX, a Document object is returned
              Document doc = sr.read(fis);
              //Element is equivalent to label. Get the root label and print it. Here is books
              Element root = doc.getRootElement();
              System.out.println(root.getName());
              //The elements under the root tag are stored in the form of ArrayList to obtain the list of sub tags
              List<Element> list = root.elements();
              for(Element e: list){
                  //Each child tag of the root node books is book. Book has Attribute and child tag Element.
                  System.out.println(e.attributeValue("id"));
                  System.out.println(e.elementText("name"));
                  System.out.println(e.elementText("info"));
                  System.out.println("-------------------------");
              }
              //Run out of closed flow
              fis.close();
          }
      }
      
      
    2. Parse from network file

      package day29;
      
      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.MalformedURLException;
      import java.net.URL;
      import java.net.URLConnection;
      
      public class Demo2 {
          public static void main(String[] args) throws IOException, DocumentException {
              String phone = "17330939825";
              //Create URL object
              URL url = new URL("http://apis.juhe.cn/mobile/get?phone=" + phone + "&dtype=xml&key=9f3923e8f87f1ea50ed4ec8c39cc9253");
              //Create a connection using a URL connection
              URLConnection connection = url.openConnection();
              //Create an input stream for this link
              InputStream is = connection.getInputStream();
              //Build parser
              SAXReader sr = new SAXReader();
              //Parse the xml file provided by this url to obtain a Document object
              Document doc = sr.read(is);
              //Get root tag
              Element root = doc.getRootElement();
              //There is a status code under the tag, which is 200, indicating a successful return
              String code = root.elementText("resultcode");
              if("200".equals(code)){
                  //Under the root tag is the result sub tag to obtain the Element
                  Element result = root.element("result");
                  //Under the result tag, there are two sub tags, province and city, which can print their contents
                  String province = result.elementText("province");
                  String city = result.elementText("city");
                  if(city.equals(province))
                      System.out.println("Home of mobile phone number:" + city);
                  else
                      System.out.println("Home of mobile phone number:" + province + city);
              }
              is.close();
          }
      }
      
      
  • XPATH parsing XML

    1. /: find from root node

    2. / /: find descendant nodes from the location of the node initiating the search

    3. .: find the current node

    4. ...: find parent node

    5. @: select attribute [@ attribute name = "value"]

      package day29;
      
      import org.dom4j.Document;
      import org.dom4j.DocumentException;
      import org.dom4j.Element;
      import org.dom4j.Node;
      import org.dom4j.io.SAXReader;
      
      import java.io.FileInputStream;
      import java.io.IOException;
      import java.sql.SQLOutput;
      import java.util.List;
      
      public class Demo4 {
          public static void main(String[] args) throws IOException, DocumentException {
              
              //Read the file and get the input stream
              FileInputStream fis = new FileInputStream("C:\\Users\\Administrator\\IdeaProjects\\Practice\\src\\day29\\Demo.xml");
              //Create resolution method
              SAXReader sr = new SAXReader();
              //After parsing the file with SAX, a Document object is returned
              Document doc = sr.read(fis);
              //Find all the name nodes through the document object + xpath
      //        List<Node> list = doc.selectNodes("//name");
      //        for(int i=0; i<list.size(); i++){
      //            //getName() and getText()
      //            System.out.println(list.get(i).getName() + ":" + list.get(i).getText());
      //        }
              //Filter Node objects with attributes and return a List. Those that meet the conditions will be stored in the List
              List<Node> list = doc.selectNodes("//book[@id='101']//name");
              for(Node e: list)
                  System.out.println(e.getName() + ":" + e.getText());
              //If only one tag is filtered out in the end, you can use SingleNode. Returns a Node object
              Node node = doc.selectSingleNode("//book[@id='102']//name");
              System.out.println(node.getName() + ":" + node.getText());
              //Run out of closed flow
              fis.close();
          }
      }
      
      
      package day29;
      
      import org.dom4j.Document;
      import org.dom4j.DocumentException;
      import org.dom4j.Element;
      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;
      
      public class Demo3 {
          public static void main(String[] args) throws IOException, DocumentException {
              String phone = "17330939825";
              //Create URL object
              URL url = new URL("http://apis.juhe.cn/mobile/get?phone=" + phone + "&dtype=xml&key=9f3923e8f87f1ea50ed4ec8c39cc9253");
              //Create a connection using a URL connection
              URLConnection connection = url.openConnection();
              //Create an input stream for this link
              InputStream is = connection.getInputStream();
              //Build parser
              SAXReader sr = new SAXReader();
              //Parse the xml file provided by this url to obtain a Document object
              Document doc = sr.read(is);
              //
              Node node = doc.selectSingleNode("//company");
              System.out.println(node.getName() + ":" + node.getText());
      
              is.close();
          }
      }
      
      
  • Generate XML using Java

    package day29;
    
    import org.dom4j.Document;
    import org.dom4j.DocumentHelper;
    import org.dom4j.Element;
    import org.dom4j.io.XMLWriter;
    
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    public class Demo5 {
        public static void main(String[] args) throws IOException {
            //Create a document object through the document helper
            Document doc = DocumentHelper.createDocument();
            //Add the first node (root node) to the document
            Element books = doc.addElement("books");
            for(int i=0; i<10; i++){
                //Create 10 book nodes in books
                Element book = books.addElement("book");
                //Add a name node to book
                Element name = book.addElement("name");
                name.setText("Journey to the West" + i);
                //Add info node to book
                Element info = book.addElement("info");
                info.setText("Learning from the West" + i);
                //Add id attribute to book
                book.addAttribute("id", 100+i+"");
            }
            //Create a file output stream
            FileOutputStream fos = new FileOutputStream("c://book.xml");
            //Convert output stream to XML stream
            XMLWriter xw = new XMLWriter(fos);
            //Write out the document
            xw.write(doc);
            fos.close();
        }
    }
    
    
    <?xml version="1.0" encoding="UTF-8"?>
    <books>
        <book id="100">
            <name>Journey to the West 0</name>
            <info>West heaven Sutra 0</info>
        </book>
        <book id="101">
            <name>Journey to the West 1</name>
            <info>Learning from the West 1</info>
        </book>
        <book id="102">
            <name>Journey to the west 2</name>
            <info>Learning from the west 2</info>
        </book>
        <book id="103">
            <name>Journey to the west 3</name>
            <info>Learning from the west 3</info>
        </book>
        <book id="104">
            <name>Journey to the west 4</name>
            <info>Learning from the west 4</info>
        </book>
        <book id="105">
            <name>Journey to the west 5</name>
            <info>Learning from the west 5</info>
        </book>
        <book id="106">
            <name>Journey to the west 6</name>
            <info>Learning from the west 6</info>
        </book>
        <book id="107">
            <name>Journey to the west 7</name>
            <info>Learning from the west 7</info>
        </book>
        <book id="108">
            <name>Journey to the West 8</name>
            <info>Learning scriptures from the West 8</info>
        </book>
        <book id="109">
            <name>Journey to the West 9</name>
            <info>Learning scriptures from the West 9</info>
        </book>
    </books>
    
  • Use of XStream (output objects in java to xml format)

    package day29;
    
    import com.thoughtworks.xstream.XStream;
    
    import java.util.Objects;
    
    public class Demo6 {
        public static void main(String[] args) {
            Book b = new Book("Romance of the Three Kingdoms", 56.2);
    
            //Use of XStream
            XStream x = new XStream();
            //Modify the node generated by a certain type (optional, default package name. Class name)
            x.alias("person", Book.class);
            //Pass in the object and start the generation
            String xml = x.toXML(b);
            System.out.println(xml);
        }
        static class Book{
            private String name;
            private double price;
    
            public Book() {
            }
    
            public Book(String name, double price) {
                this.name = name;
                this.price = price;
            }
    
            @Override
            public String toString() {
                return "Book{" +
                        "name='" + name + '\'' +
                        ", price=" + price +
                        '}';
            }
    
            @Override
            public boolean equals(Object o) {
                if (this == o) return true;
                if (o == null || getClass() != o.getClass()) return false;
                Book book = (Book) o;
                return Double.compare(book.price, price) == 0 &&
                        Objects.equals(name, book.name);
            }
    
            @Override
            public int hashCode() {
                return Objects.hash(name, price);
            }
    
            public String getName() {
                return name;
            }
    
            public void setName(String name) {
                this.name = name;
            }
    
            public double getPrice() {
                return price;
            }
    
            public void setPrice(double price) {
                this.price = price;
            }
        }
    }
    
    

JSON

brief introduction

JSON: Javascript object notation is a lightweight data exchange format

Object format

Now describe a book
java
	class Book{
		private String name;
		private String info;
		get/set...
	}
	
js
	var b = new object();
	b.name = "Romance of the Three Kingdoms";
	b.info = "Xinghan brilliant";
XML

	<book>
		<name>Romance of the Three Kingdoms</name>
		<info>If out of it</info>
	</book>
	
JSON
	{
		"name":"Romance of the Three Kingdoms"
		"info":"If the sun and moon travel out of it"
	}

Array format

In JSON format, it can be nested with objects, such as [element 1, element 2...]

JAVA and JSON parsing

Gson

Object < ------> JSON format string, and pay attention to the conversion and format of the array

package day29;

import com.google.gson.Gson;

import java.util.HashMap;
import java.util.List;

public class Demo7 {
    public static void main(String[] args) {
        //Create Gson object
        Gson g = new Gson();
        Book b = new Book(100100, "Water Margin", "Liang Shanbo 108 hero");
        //Converts the Book object to a string in Gson format
        String s = g.toJson(b);
        System.out.println(s);

        //{"id":100100,"name": "outlaws of the marsh", "info": "Liang Shanbo 108 hero"}
        String str = "{\"id\":100100,\"name\":\"Water Margin\",\"info\":\"Liang Shanbo 108 hero\"}";
        //Converts the Json string back to the Book object
        Book book = g.fromJson(str, Book.class);
        System.out.println(book.getId() + "; " + book.getName() + "; " + book.getInfo());

        //{"id":100100,"name": "outlaws of the marsh", "info": "Liang Shanbo 108 hero", "page": ["the wind is roaring", "the horse is barking", "the Yellow River is roaring]}
        String newStr = "{\"id\":100100,\"name\":\"Water Margin\",\"info\":\"Liang Shanbo 108 hero\", \"page\":[\"The wind is roaring\",\"The horse is barking\",\"The Yellow River is roaring\"]}";
        HashMap map = g.fromJson(newStr, HashMap.class);
        //The array type in Json will actually be converted to ArrayList
        System.out.println(map.get("page"));
        System.out.println(map.get("page").getClass());
        //Strong transformation with the concept of polymorphism
        List list = (List)map.get("page");
        System.out.println(list.get(1));
    }
    static class Book{
        private int id;
        private String name;
        private String info;

        public Book(int id, String name, String info) {
            this.id = id;
            this.name = name;
            this.info = info;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getInfo() {
            return info;
        }

        public void setInfo(String info) {
            this.info = info;
        }
    }
}

FastJson object < ------ > JSON string
package day29;

import com.alibaba.fastjson.JSON;

import java.util.List;

public class Test {
    public static void main(String[] args) {
        //Convert object to JSON string
        Book book = new Book(10010, "Romance of the Three Kingdoms", "keep loyal and devoted to the last");
        String s = JSON.toJSONString(book);
        System.out.println(s);

        //{"id":10010,"name": "Romance of the Three Kingdoms", "info": "devote yourself to death"}

        //Convert the above JSON string into a Book object
        String str = "{\"id\":10010,\"name\":\"Romance of the Three Kingdoms\",\"info\":\"keep loyal and devoted to the last\"}";
       Book book1 = JSON.parseObject(s,Book.class);
        System.out.println(book1.toString());

        //Convert JSON string with array to ArrayList
        //["Penini","Xiaoxiong","Donglin"];
        List<String> arr1 = JSON.parseArray("[\"Penini\",\"Xiaoxiong\",\"Donglin\"]", String.class);
        System.out.println(arr1.get(1));
    }
}

package day29;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;

public class Book {

        private int id;
        private String name;
        private String info;

        public Book(int id, String name, String info) {
            super();
            this.id = id;
            this.name = name;
            this.info = info;
        }

        @Override
        public String toString() {
            return "Book{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", info='" + info + '\'' +
                    '}';
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getInfo() {
            return info;
        }

        public void setInfo(String info) {
            this.info = info;
        }

}

Keywords: Java JSON xml

Added by frost on Wed, 02 Mar 2022 01:37:57 +0200