1.Nested Classes (including Inner Classes)
Gson可以序列化和反序列化静态内部类
Gson can serialize static nested classes quite easily.
Gson can also deserialize static nested classes. However, Gson can not automatically deserialize the pure inner classes
since their no-args constructor also need a reference to the containing Object which is not available at the time of deserialization.
You can address this problem by either making the inner class static or by providing a custom InstanceCreator for it.
public class A {
public String a;
class B {
public String b;
public B() {
// No args constructor for B
}
}
}
NOTE: The above class B can not (by default) be serialized with Gson.
我试了一下,有一些不太一样,可能是没有完全理解英文的意思,或理解错了,欢迎指正;
默认的话,内部类没有默认进行序列化,即使是静态内部类也没有序列化;
内部类也可以反序列化
package org.ygy.demo;
public class A {
public String name_a = "default a";
class B {
public String name_b = "default b";
public String toString() {
return "name_b:" + name_b;
}
}
class C {
public String name_c = "default c";
}
static class D {
public String name_d = "default d";
public String toString() {
return "name_d:" + name_d;
}
}
}
结果:
@Test
public void testNested() {
A a = new A();
String json_a = gson.toJson(a);
System.out.println("json_a" + json_a);
A.B b = a.new B();
b.name_b = "okokok";
String json_b = gson.toJson(b);
System.out.println("json_b" + json_b);
A.B b2 = a.new B();
b2 = gson.fromJson(json_b , A.B.class);
System.out.println(b2);
A.D d = new A.D();
d.name_d = "hello";
String json_d = gson.toJson(d);
System.out.println("json_d" + json_d);
A.D d2 = gson.fromJson(json_d , A.D.class);
System.out.println(d2);
}
InstanceCreator
public class InstanceCreatorForB implements InstanceCreator<A.B> {
private final A a;
public InstanceCreatorForB(A a) {
this.a = a;
}
public A.B createInstance(Type type) {
return a.new B();
}
}