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如何序列化内部类的详细内容,更多关于gson 序列化的资料请关注萬仟网其它相关文章!
希望与广大网友互动??
点此进行留言吧!