目录
1、简介
JSON:JavaScript Object Notation,JS对象简谱,是一种轻量级数据交换格式。
2、格式
{
“name”:"西游记“,
”info":"西天取经"
}
一个对象由一个大括号表示,括号中表示的是对象的属性,通过键值对描述对象的属性
格式:
键与值之间使用冒号,键值对之间使用逗号间隔
3、GSON解析
将JSON字符串转为对象
1、引入jar包
2、对象=new GSON().fromJson(JSON字符串,对象类型.class);
public class Demo2 {
public static void main(String[] args) {
//1. 创建Gson对象
Gson g = new Gson();
//2. 转换 : {"id":"100","name":"金苹果","info":"种植苹果真辛苦"}
Book b = g.fromJson("{\"id\":\"100\",\"name\":\"金苹果\",\"info\":\"种植苹果真辛苦\"}", Book.class);
System.out.println(b.getId());
}
}
将对象转为GSON字符串
String json = new GSON().toJson(对象);
public class Demo1 {
public static void main(String[] args) {
/*//1. 创建Gson对象
Gson g = new Gson();
//2. 转换
Book b = new Book("100","金苹果","种植苹果真辛苦");
String s = g.toJson(b);
System.out.println(s);*/
//1. 创建Gson对象
//2. 转换
Book b = new Book("100", "金苹果", "种植苹果真辛苦");
String s = new Gson().toJson(b);
System.out.println(s);
}
}
4、FastJson解析
将JSON字符串转为对象
1、引入jar包
2、类型 对象名 = JSON.parseObject(JSON字符串,类型.class);或list<类型> list = JSON.parseArray(JSON字符串,类型.class);
public class Demo5 {
public static void main(String[] args) {
//1. 转换 : {"id":"1002","info":"床前明月光,地上鞋一堆","name":"唐诗三百首"}
Book book = JSON.parseObject("{\"id\":\"1002\",\"info\":\"床前明月光,地上鞋一堆。\",\"name\":\"唐诗三百首\"}", Book.class);
System.out.println(book.getId());
}
}
public class Demo6 {
public static void main(String[] args) {
//1. 转换 : ["一二三","二三四","三四五"]
List<String> strings = JSON.parseArray("[\"一二三\",\"二三四\",\"三四五\"]", String.class);
System.out.println(strings.get(1));
}
}
将对象转为JSON字符串
1、引入jar包
String json = JSON.toJSONString(对象)
public class Demo4 {
public static void main(String[] args) {
Book book = new Book("1002","唐诗三百首","床前明月光,地上鞋一堆。");
//1. 转换
String json = JSON.toJSONString(book);
System.out.println(json);
}
}