discomarathon / google-gson

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

Having an inner class gives this error - No-args constructor for B does not exist. #135

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?

I have a Java representation of the JSON object. When I declared something
like this -

public class A{
   public String i;
   public int t;
  public B[] q;
//no arg constructor for A
   class B{
       public String j;
       public String[] k;
       //no arg constructor for B
   }
}

It throws an exception saying B does not have a no arg constructor. when I
debugged, the constructor for B is actually being passed as B(A).

I could get it working by taking B out of A but shouldn't it be working as
is? you don't want to create a separate class just for 2 variables right?
This is a a very basic case that is supposed to work.

What is the expected output? What do you see instead?
Expecetd to return an instance of A. But I see the following error.
"No-args constructor for B does not exist. Register an InstanceCreator with
Gson for this type to fix this problem."

What version of the product are you using? On what operating system?
1.3

Please provide any additional information below.

Original issue reported on code.google.com by radha.te...@gmail.com on 8 Jul 2009 at 10:04

GoogleCodeExporter commented 9 years ago
You can use Gson to serialize/deserialize nested classes; however, the nested 
classes
need to be "static" nested classes.

Note that the Java language has two types of "nested" classes:
1. Inner Class
2. Static Nested Class

An Inner Class has an implicit reference to the "this" instance of the outer 
class. 
This is why an inner class can access the private instance members of its outer 
class.

A Static Nested Class does not get this implicit reference.  You can have it 
store a
reference to A, but you will need to explicitly pass in a reference to the 
outer class.

Try changing your example as follows:
public class A {
  public String i;
  public int t;
  public B[] q;

  //no arg constructor for A

  static class B {
       public String j;
       public String[] k;
       //no arg constructor for B
   }
}

Hope this helps,
Joel

Original comment by joel.leitch@gmail.com on 29 Sep 2009 at 5:56