desaikush210 / google-gson

Automatically exported from code.google.com/p/google-gson
0 stars 0 forks source link

User guide is wrong: Inner classes can now be serialized/deserialized? #534

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
The user guide states:

https://sites.google.com/site/gson/gson-user-guide#TOC-Nested-Classes-including-
Inner-Classes-

"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."

This is no longer true (I think because of UnsafeAllocator?), and should be 
documented. The example, which previously didn't work, now does. See the 
following:

public class A {
  public String a; 

  public class B {
    public String b; 

    public B() {
    }
  }

  public static void main(String[] arguments) {
    Gson gson = new Gson();
    B b = new A().new B();

    String json = gson.toJson(b);
    System.out.println("gson.toJson(" + b + ") = " + json);
    B b2 = gson.fromJson(json, B.class);
    System.out.println("gson.fromJson(..., B.class) = " + b2);
  }
}

The output of this is:

gson.toJson(co.mitro.core.server.data.A$B@7c97cb70) = {}
gson.fromJson(..., B.class) = co.mitro.core.server.data.A$B@b45ad3d

HOWEVER: If you try to reference the parent class from b2, you get a 
NullPointerException, which is fairly surprising and "dangerous." This needs to 
at least be documented! The debate about if this is the right default is a 
different discussion (I know that GsonBuilder.disableInnerClassSerialization() 
can turn this off)

Original issue reported on code.google.com by e...@evanjones.ca on 26 Sep 2013 at 2:27