json是什么?
JSON是一种类似 XML的语言,是用了存储和交换文本信息的语法。它的全称为JavaScript Object Notation(JavaScript 对象表示法)。与xml对比,它更小、更快,更易解析。
json解析的方式
- 使用谷歌 gson jar包进行解析
- 使用阿里 fastjson jar包进行解析
idea 导jar包方式
gson和fastjson jar包下载地址
链接:https://pan.baidu.com/s/1BwQt5IjmftnEy7AUHCn_ZQ
提取码:1234
先创建Person类
public class Person {
private int id;
private String name;
private String info;
public Person() {
}
public Person(int id, String name, String info) {
this.id = id;
this.name = name;
this.info = info;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return id == person.id && Objects.equals(name, person.name) && Objects.equals(info, person.info);
}
@Override
public int hashCode() {
return Objects.hash(id, name, info);
}
@Override
public String toString() {
return "Person{" +
"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;
}
gson使用方式
public class GosnTest {
public static void main(String[] args) {
// 创建谷歌 Gosn 对象
Gson gson = new Gson();
// 创建人对象,并赋值
Person person = new Person(1,"豪哥","身高185");
// 进行对象转换json
String s = gson.toJson(person, Person.class);
System.out.println(s);
// 解析json,转换对象格式 {"id":1,"name":"豪哥","info":"身高185"}
Person person = gson.fromJson("{\"id\":1,\"name\":\"豪哥\",\"info\":\"身高185\"}", Person.class);
System.out.println(person.getId());
// 解析json,转换map格式 {"id":1,"name":"豪哥","info":"身高185","page":["长期安民活跃鬼","红红火火恍恍惚惚"]}
HashMap date = gson.fromJson("{\"id\":1,\"name\":\"豪哥\",\"info\":\"身高185\",\"page\":[\"长期安民活跃鬼\",\"红红火火恍恍惚惚\"]}", HashMap.class);
System.out.println(date.get("id"));
// 读取list集合
List page = (List) date.get("page");
System.out.println(page.get(1));
}
}
fastjson使用方式
public class FastJSONTest {
public static void main(String[] args) {
// 获取Person对象,并赋值
Person person = new Person(100, "大豪", "身高190");
// 对象转为json
String s = JSON.toJSONString(person);
System.out.println(s);
// json转换为对象 {"id":100,"info":"身高190","name":"大豪"}
Person person = JSON.parseObject("{\"id\":100,\"info\":\"身高190\",\"name\":\"大豪\"}", Person.class);
System.out.println(person.getId());
// json转为
//json转换为集合 : ["一二三","二三四","三四五"]
List<String> strings = JSON.parseArray("[\"一二三\",\"二三四\",\"三四五\"]", String.class);
System.out.println(strings.get(1));
}
}