使用gson解析json数据

2025-10-23 16:18:43

1、首先创建测试代码实体类,用于解析json数据之后存放数据的实体类,年级Grade类

private String course;//课程字段

private String score;//分数字段

使用gson解析json数据

2、再创建一个学生实体类,Student类

private String name;//学生名字

private int age;//年纪

private String sex;//性别

private Grade grade;//年级

使用gson解析json数据

3、创建TestGson测试类,添加一个main方法,作为测试入口

使用gson解析json数据

4、首先解析单条无嵌套Json数据的

String jsonStr = "{'name':'Tom', 'age':30, 'sex':'male'}";

Gson gson = new Gson();

Student student = gson.fromJson(jsonStr, Student.class);

System.out.println(student);

运行查看结果

使用gson解析json数据

5、//解析单条有嵌套的Json数据

String jsonStr1 = "{'name':'Tom', 'age':30, 'sex':'male', 'grade':{'course':'java','score':'100'}}";

Gson gson1 = new Gson();

Student student1 = gson1.fromJson(jsonStr1, Student.class);

System.out.println(student1);

使用gson解析json数据

6、//解析Json数组

String jsonStr2 = "[{'name':'Tom', 'age':30, 'sex':'male', 'grade':{'course':'java','score':'100'}}," +

       "{'name':'Lili', 'age':25, 'sex':'female', 'grade':{'course':'java','score':'100'}}]";

Gson gson2 = new Gson();

List<Student> students = gson2.fromJson(jsonStr2, new TypeToken<List<Student>>(){}.getType());

System.out.println(students);

使用gson解析json数据

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢