[Json] GSON 数据容错
GSON
GSON是Googel公司开发的用于解析json的类库。可以很轻松地让程序员将java对象转换成JSON格式,或者将JSON格式的对象转换成Java对象。
GSON的github地址:https://github.com/google/gson/
GSON的下载地址:https://search.maven.org/artifact/com.google.code.gson/gson/2.8.6/jar
使用maven,引入依赖即可
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10</version>
</dependency>
使用Gson解析JSON字符串
//对象 -> JSON字符串
Person p1 = new Person("小明", 20);
String json = new Gson().toJson(p1);
System.out.println(json);
//JSON字符串 -> 对象
//如果需要转换: {"name":"小明","age":20}
Person p = new Gson().fromJson("{\"name\":\"小明\",\"age\":20}", Person.class);
System.out.println(p.getName());
System.out.println(p.getAge());
//Json字符串转换为Map集合
//如果需要转换: {"name":"小明","age":20}
HashMap map = new Gson().fromJson("{\"name\":\"小明\",\"age\":20}", HashMap.class);
System.out.println("姓名:" + map.get("name"));
System.out.println("年龄:" + map.get("age"));
浙公网安备 33010602011771号