[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"));

posted @   NetUSA  阅读(46)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示