JSON解析
针对JSON解析的问题,我们使用两种解析方式,一种是谷歌开发的Gson,一种是阿里开发的Fastson。
并且一般我们使用过程,就是把对象转换成JSON格式 或者 JSON格式的字符串转换为Java的对象
Gson
将对象转换为JSON字符串
在我们引入jar包之后只需要用以下代码就能转换了:
String json = new Gson().toJSON(要转换的对象);
示例:
Book book = new Book("100","金苹果","种苹果之路");
String text = new Gson().toJson(book);
System.out.println(text);
结果:
{"id":"100","name":"金苹果","info":"种苹果之路"}
将JSON字符串转换为对象
通用模式为:
对象 = new Gson().fromJson(JSON字符串,对象类型.class);
对此进行试验的代码演示:
//1. 创建JSON对象
Gson g = new Gson();
//2. 转换{"id":"100","name":"金苹果","info":"种苹果之路"}
Book book = g.fromJson("{\"id\":\"100\",\"name\":\"金苹果\",\"info\":\"种苹果之路\"}",Book.class);
System.out.println(book.getId());
结果:
100
FastJson
将对象转换为JSON字符串
同样的需要引入对应的jar包,引入之后通用模式为:
String json=JSON.toJSONString(要转换的对象);
示例:
Book book = new Book("1002","唐诗300首","窗前明月光,疑是地上霜");
//1. 转换
String text = JSON.toJSONString(book);
System.out.println(text);
结果:
{"id":"1002","info":"窗前明月光,疑是地上霜","name":"唐诗300首"}
将JSON字符串转换为对象
通用模式分为两种:
一种是转换为对象,一种是转换为数组用List储存
类型 对象名=JSON.parseObject(JSON字符串, 类型.class);
List<类型> list=JSON.parseArray(JSON字符串,类型.class);
示例:
//1.转换{"id":"1002","info":"窗前明月光,疑是地上霜","name":"唐诗300首"}
Book book = JSON.parseObject("{\"id\":\"1002\",\"info\":\"窗前明月光,疑是地上霜\",\"name\":\"唐诗300首\"}",Book.class);
System.out.println(book.getId());
//转换数组 ["一一一","二二二","三四五"]
List<String> strings= JSON.parseArray("[\"一一一\",\"二二二\",\"三四五\"]",String.class);
System.out.println(strings.get(1));
}
结果:
1002
二二二
以上就是JSON解析的全部内容了