XML与JSON
XML
特性:
- xml具有平台无关性,是一门独立的标记语言
- xml具有自我描述性
在什么平台打开都是一样的,语言平台或mac.windows中打开相同
JSON解析
案例:GSON
将一个类转换成JSON格式:
package com.fan.demo02;
import com.google.gson.Gson;
import java.util.Objects;
/**
* @Author: fyw
* @Description:
* @Date Created in 2021-08-25 1:07
* @Modified By:
*/
public class Demo01 {
public static void main(String[] args) {
//1. 创建json对象
Gson g = new Gson();
Book book = new Book("金苹果","种植苹果真辛苦","100");
String s = g.toJson(book);
System.out.println(s);
}
}
class Book{
private String name;
private String info;
private String id;
public Book() {
}
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
", info='" + info + '\'' +
", 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;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Book book = (Book) o;
return Objects.equals(name, book.name) && Objects.equals(info, book.info) && Objects.equals(id, book.id);
}
@Override
public int hashCode() {
return Objects.hash(name, info, id);
}
public Book(String name, String info, String id) {
this.name = name;
this.info = info;
this.id = id;
}
}
将一个JSON格式转换成一个HashMap集合–>>相当于键值对的存储
注意:如果json中存在一个类似于数组的块转换后—>>>是一个ArrayList集合
package com.fan.demo02;
import com.google.gson.Gson;
import java.awt.*;
import java.util.ArrayList;
import java.util.HashMap;
/**
* @Author: fyw
* @Description:
* @Date Created in 2021-08-25 1:32
* @Modified By:
*/
public class Demo02 {
public static void main(String[] args) {
//{"name":"金苹果","info":"种植苹果真辛苦","id":"100","page":["锄禾日当午","汗滴禾下土","谁知盘中餐"]}
Gson json = new Gson();
HashMap hashMap = json.fromJson("{\"name\":\"金苹果\",\"info\":\"种植苹果真辛苦\",\"id\":\"100\",\"page\":[\"锄禾日当午\",\"汗滴禾下土\",\"谁知盘中餐\"]}",
HashMap.class);
ArrayList list = (ArrayList) hashMap.get("page");
System.out.println(list.get(0).getClass());
}
}