Java Basic 25~XML and JSON parsing

Like you who love programming!
Learn SpringBoot actual combat course https://edu.csdn.net/course/detail/31433
Learn SpringCloud introductory course https://edu.csdn.net/course/detail/31451


Preface

JSON and XML are two common data formats for project development. JSON is often used for network communication, and XML is often used for configuration files. Let's have a brief understanding of them.

JSON

The concept of JSON

Is a lightweight data exchange format. Easy to read and write. At the same time, it is easy to parse and generate by machine, and it is the current mainstream data exchange format.

JSON format:

Single object:

{"number":"888888","brand":"福特","price":80000.0}

Array:

 [ {"number":"888888","brand":"福特","price":80000.0},			 
  {"number":"777777","brand":"奥迪","price":280000.0},
  {"number":"666666","brand":"奔驰","price":1180000.0}]

JSON parsing

There are many packages for JSON parsing, such as Google’s gson, Ali’s FastJson, and Jackson, etc.

Use of gson
Download Gson and import it into the project.
Address: https://download.csdn.net/download/u013343114/14919183

Create a Gson object:

Gson gson = new Gson();

Convert the object to a JSON string:

gson.toJson(对象);

Parse the JSON string into an object:

gson.fromJson(JSON字符串, 类名.class);

Parse the JSON string into a collection of objects:

gson.fromJson(JSON字符串,new TypeToken<集合类型>(){}.getType());
class Car{
    private String number;
    private String brand;
    private double price;

    public Car(String number, String brand, double price) {
        this.number = number;
        this.brand = brand;
        this.price = price;
    }

    public Car() {
    }

    @Override
    public String toString() {
        return "Car{" +
                "number='" + number + '\'' +
                ", brand='" + brand + '\'' +
                ", price=" + price +
                '}';
    }
}

public class Demo {

    public static void main(String[] args) {
        Gson gson = new Gson();
        Car car = new Car("66666","BMW",60000);
        //Java对象转JSON
        String carJson = gson.toJson(car);
        System.out.println("单个JSON:" + carJson);
        //JSON转Java对象
        Car car1 = gson.fromJson(carJson,Car.class);
        System.out.println("Java对象:" + car1);
        List<Car> cars = Arrays.asList(new Car("77777","Benz",90000),
                new Car("88888","Benz",90000),
                new Car("99999","Benz",90000));
        //Java集合转JSON
        String carsJson = gson.toJson(cars);
        System.out.println("JSON数组:" + carsJson);
        //JSON转Java集合
        List<Car> cars1 = gson.fromJson(carsJson,new TypeToken<List<Car>>(){}.getType());
        System.out.println("Java集合:" + cars1);
    }
}

Insert picture description here

XML

The concept of XML

Extensible markup language, flexible writing, strong readability, and labels can be expanded freely. It is a common format for program configuration files and data exchange.

XML example:

<?xml version="1.0" encoding="utf-8" ?>  
<persons>
	<!--第一个人-->
	<person id="1">
		<name>张三</name>
		<age>30</age>
		<address>
			<city>武汉</city>
			<street>解放大道1001号</street>
		</address>
	</person>
	<!--第二个人-->
	<person id="2">
		<name>李四</name>
		<age>33</age>
		<address>
			<city>武汉</city>
			<street>光谷大道1001号</street>
		</address>
	</person>
</persons>  

Description:

  • <?xml version="1.0" encoding="utf-8" ?> is the XML file declaration, version is the version, encoding is the character encoding
  • The persons tag is defined by itself and belongs to the root node. An XML has one and only one root node.
  • <!–The first person–> is an XML comment
  • person belongs to a child node, id="1" is a freely defined attribute
  • Zhang San is a child node of person, <> is the name of the node, and Zhang San is the value of the node
  • Nodes must appear in pairs and be case sensitive

Compare JSON and XML

Use JSON and XML to define the same data:
JSON

[ {"number":"888888","brand":"福特","price":80000.0},			 
  {"number":"777777","brand":"奥迪","price":280000.0},
  {"number":"666666","brand":"奔驰","price":1180000.0}]

XML

<?xml version="1.0" encoding="utf-8" ?>
<cars>
	<car>
		<number>888888</number>
		<brand>BMW</brand>
		<price>888880</price>
		</car>
	<car>
		<number>888888</number>
		<brand>BMW</brand>
		<price>888880</price>
	</car>
</cars>

Comparing JSON and XML is not difficult to find:

  • The JSON code is more concise and occupies less bandwidth during network transmission. It is the mainstream data communication format
  • XML code is more complex, more descriptive, and more suitable for configuration files

XML parsing

Use Dom4j to parse XML

Steps for usage

  1. Create a SAXReader object:
SAXReader reader = new SAXReader();
  1. Read document
Document doc = reader.read(new File(path));
  1. Get the root node:
Element root = doc.getRootElement();
  1. The iterator of the obtained node is used to traverse the child nodes:
Iterator it = root.elementIterator();
  1. Traverse the child nodes:
while(it.hasNext()){
	Element e = (Element) it.next();
}
  1. Read node
读取节点的属性:
e.attributeValue("id");
读取节点的名称:
e.getName();
读取节点的值:
e.getStringValue();

Parse c3p0-config.xml in the src directory

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    <default-config>
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/netdisk</property>
        <property name="user">root</property>
        <property name="password">123456</property>
    </default-config>
</c3p0-config>

Parsing code

/**
 * 读取XML配置文件
 */
public class XMLDemo{
	public static void main(String[] args){
		//创建读取器
		SAXReader reader = new SAXReader();
		//读取src下的xml文件,获得文档对象
		try {
			Document doc = reader.read(MyDBUtils.class.getClassLoader().getResourceAsStream("c3p0-config.xml"));
			//获得根节点
			Element root = doc.getRootElement();
			//获得子节点default-config
			Element config = root.element("default-config");
			//读取default-config下的所有子节点
			List<Element> elements = config.elements();
			//遍历子节点
			for(Element ele : elements ){
				//判断property节点的名称
				if("property".equals(ele.getName())){
					//读取name属性的值
					String name = ele.attribute("name").getValue();
					//判断属性的值
					switch(name){
					case "driverClass":
						//读取节点的文字
						driverClass = ele.getText();
						break;
					case "jdbcUrl":
						//读取节点的文字
						url = ele.getText();
						break;
					case "user":
						//读取节点的文字
						user = ele.getText();
						break;
					case "password":
						//读取节点的文字
						pwd = ele.getText();
						break;
					}
				}
			}
			System.out.println(driverClass);
			System.out.println(url);
			System.out.println(user);
			System.out.println(pwd);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

End


If you need to learn other Java knowledge, poke here ultra-detailed knowledge of Java Summary

Guess you like

Origin blog.csdn.net/u013343114/article/details/112976901