Gson如何实现序列化内部类?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
1 Gson处理成员内部类
1.1 编写核心类
MainApp:
package com.yiidian.gson; import com.google.gson.Gson; public class MainApp { public static void main(String args[]) { Student student = new Student(); student.setRollNo(1); Student.Name name = student.new Name(); name.firstName = "Mahesh"; name.lastName = "Kumar"; student.setName(name); Gson gson = new Gson(); //序列化 String jsonString = gson.toJson(student); System.out.println(jsonString); //反序列化 student = gson.fromJson(jsonString, Student.class); System.out.println("Roll No: "+ student.getRollNo()); System.out.println("First Name: "+ student.getName().firstName); System.out.println("Last Name: "+ student.getName().lastName); String nameString = gson.toJson(name); System.out.println(nameString); name = gson.fromJson(nameString,Student.Name.class); System.out.println(name.getClass()); System.out.println("First Name: "+ name.firstName); System.out.println("Last Name: "+ name.lastName); } } class Student { private int rollNo; private Name name; public int getRollNo() { return rollNo; } public void setRollNo(int rollNo) { this.rollNo = rollNo; } public Name getName() { return name; } public void setName(Name name) { this.name = name; } //成员内部类 class Name { public String firstName; public String lastName; } }
1.2 运行测试
2 Gson处理静态内部类
2.1 编写核心类
MainApp:
package com.yiidian.gson; import com.google.gson.Gson; public class MainApp { public static void main(String args[]) { Student student = new Student(); student.setRollNo(1); Student.Name name = new Student.Name(); name.firstName = "Mahesh"; name.lastName = "Kumar"; student.setName(name); Gson gson = new Gson(); String jsonString = gson.toJson(student); System.out.println(jsonString); student = gson.fromJson(jsonString, Student.class); System.out.println("Roll No: "+ student.getRollNo()); System.out.println("First Name: "+ student.getName().firstName); System.out.println("Last Name: "+ student.getName().lastName); String nameString = gson.toJson(name); System.out.println(nameString); name = gson.fromJson(nameString,Student.Name.class); System.out.println(name.getClass()); System.out.println("First Name: "+ name.firstName); System.out.println("Last Name: "+ name.lastName); } } class Student { private int rollNo; private Name name; public int getRollNo() { return rollNo; } public void setRollNo(int rollNo) { this.rollNo = rollNo; } public Name getName() { return name; } public void setName(Name name) { this.name = name; } //静态内部类 static class Name { public String firstName; public String lastName; } }
2.2 运行测试
关于Gson如何实现序列化内部类问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。