user2504767
user2504767

Reputation:

How to implement a default constructor to using a complex object structure in Json?

i work with json and junit. I want to create a complex object structure with Json, but i can´t create this structure, since i get this exception:

Register an InstanceCreator with Gson for this type may fix this problem.

The problem is, that one of the java classes in the json structure doesn´t have default constructor. I have found this introduction to this topic:

http://google-gson.googlecode.com/svn/tags/1.2.3/docs/javadocs/com/google/gson/InstanceCreator.html

Here is the java class, but i don´t now, how i can create the default constructor in the right way. Here is a try, but it creates a compilation error:

public ProductModel{

    private Product product;

    // My new default constructor, but it doesn´t work
    public ProductModel() {
        this(Product.class);
    }

    public ProductModel(final Product product) {
        super();
        this.product = product;
    }
}

Thanks for helping me !

Greetz Marwief

Upvotes: 1

Views: 239

Answers (1)

Kennet
Kennet

Reputation: 5796

A default constructor is the same as a no arguments constructor. A default constructor is implicit until you declare one by yourself. In your snippet you are trying use that (default) with the other constructor with an invalid type. The Person class is not the same as an instance (object) of Person class. So instead you must create an instance of that as in the following:

public ProductModel{

private Product product;

public ProductModel() {
    this(new Product()); 
}

public ProductModel(final Product product) {
    super();
    this.product = product;
}

}

GSon requires a default constructor so you might have to come up with another method to feed your ProductModel. A suggestion could be an init method

    public class ProductModel {

    private Product product;

    public ProductModel() {

    }

    public void init(Product product){
        this.product = product;
    }
}

(In the above case the constructor doesn't do anything and can therefore be removed).

Hope this can be of some help.

Upvotes: 1

Related Questions