json
package jsonTask; import com.google.gson.Gson; import java.util.HashMap; public class Demo2Gson { public static void main(String[] args) { String jsonStr="{\"id\":\"1500100001\",\"name\":\"施笑槐\",\"age\":\"22\",\"gender\":\"女\",\"clazz\":\"文科六班\"}"; System.out.println(jsonStr); //Gson解析json字符串 Gson gson = new Gson(); //传入两个参数,一个字符串,一个解析的格式,用反射来写 HashMap<String, String> map = new HashMap<String, String>(); HashMap hashMap = gson.fromJson(jsonStr, map.getClass()); System.out.println(hashMap); System.out.println(hashMap.get("id")); //将json解析成java对象 Student s = gson.fromJson(jsonStr, Student.class); System.out.println(s); //将java对象转化为json Student student = new Student("1222", "张三", 26, "男", "一班"); String s1 = gson.toJson(student); System.out.println(s1);
//输出结果
{"id":"1500100001","name":"施笑槐","age":"22","gender":"女","clazz":"文科六班"}
{gender=女, name=施笑槐, id=1500100001, clazz=文科六班, age=22}
1500100001
Student(id=1500100001, name=施笑槐, age=22, gender=女, clazz=文科六班)
{"id":"1222","name":"张三","age":26,"gender":"男","clazz":"一班"}
}
}
需要先导依赖
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
public class Demo3 { public static void main(String[] args) { String jsonStr="{\"id\":\"1500100001\",\"name\":\"施笑槐\",\"age\":\"22\",\"gender\":\"女\",\"clazz\":\"文科六班\"}"; JSONObject jsonObject = JSON.parseObject(jsonStr); Object id = jsonObject.get("id"); System.out.println(id); Student student = JSON.parseObject(jsonStr, Student.class); int age = student.getAge(); System.out.println(age);
//输出结果
1500100001
22
}
}
依赖:
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构