在这篇文章中,我们将讨论如何对具有内部类的类进行序列化/反序列化。
让我们看看一个嵌套类的序列化/反序列化的例子。
package net.javaguides.gson;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
*
* @author Ramesh Fadatare
*
*/
public class GSONNestedClassesExample {
public static void main(String[] args) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
OuterClass outerClass = new OuterClass();
outerClass.setValue1("value1");
outerClass.setValue2("value2");
OuterClass.InnerClass innerClass = outerClass.new InnerClass();
innerClass.value3 = "value3";
innerClass.value4 = "value4";
outerClass.setInnerClass(innerClass);
String jsonStr = gson.toJson(outerClass);
System.out.println(jsonStr);
}
}
class OuterClass {
private String value1;
private String value2;
private InnerClass innerClass;
public String getValue1() {
return value1;
}
public void setValue1(String value1) {
this.value1 = value1;
}
public String getValue2() {
return value2;
}
public void setValue2(String value2) {
this.value2 = value2;
}
public void setInnerClass(InnerClass innerClass) {
this.innerClass = innerClass;
}
public InnerClass getInnerClass() {
return innerClass;
}
class InnerClass {
public String value3;
public String value4;
}
}
输出:
{
"value1": "value1",
"value2": "value2",
"innerClass": {
"value3": "value3",
"value4": "value4"
}
}
让我们看看一个带有静态类的序列化/反序列化的例子。
package net.javaguides.gson;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
*
* @author Ramesh Fadatare
*
*/
public class GSONNestedClassesExample {
public static void main(String[] args) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
OuterClass outerClass = new OuterClass();
outerClass.setValue1("value1");
outerClass.setValue2("value2");
OuterClass.InnerClass innerClass = new OuterClass.InnerClass();
innerClass.value3 = "value3";
innerClass.value4 = "value4";
outerClass.setInnerClass(innerClass);
String jsonStr = gson.toJson(outerClass);
System.out.println(jsonStr);
}
}
class OuterClass {
private String value1;
private String value2;
private InnerClass innerClass;
public String getValue1() {
return value1;
}
public void setValue1(String value1) {
this.value1 = value1;
}
public String getValue2() {
return value2;
}
public void setValue2(String value2) {
this.value2 = value2;
}
public void setInnerClass(InnerClass innerClass) {
this.innerClass = innerClass;
}
public InnerClass getInnerClass() {
return innerClass;
}
static class InnerClass {
public String value3;
public String value4;
}
}
输出:
{
"value1": "value1",
"value2": "value2",
"innerClass": {
"value3": "value3",
"value4": "value4"
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.javaguides.net/2018/10/gson-serializing-inner-classes-example.html
内容来源于网络,如有侵权,请联系作者删除!