Skip to content Skip to sidebar Skip to footer

No-args Constructor For Class XXX Does Not Exist

I am new to Android development. Here, I am making a GET call like this - protected String doInBackground(String... params) { List nameValuePairs

Solution 1:

The Gson user guide (https://sites.google.com/site/gson/gson-user-guide) tells you that a well behaved class (meant for serialization and deserialization) should have a no argument constructor. If this is not there, it advises you to use InstanceCreator.

Even if you do not have a constructor, Gson will create an ObjectConstructor for your class. But this is not safe always and has it's own limitations. This question on SO goes more into the details: Is default no-args constructor mandatory for Gson?

NOTE: Please see that if this is an inner class, then it MUST have a constructor as explained in the documentation.

EDIT: Your json is an array. So you need to have the specified number of array objects in the containing class. So you can do the following and then cast:

public class ProductDetailArray {

    public ProductDetailArray[] array;

    public static ProductDetail {
        public ProductDetail() {} // You can also make the constructor private if you don't want anyone to instantiate this

        public int Id;
        public String Name; 
    }
}

Once you cast your json similarly as before:

ProductDetailArray obj = GsonBuilder.create().fromJson(response, ProductDetailArray.class);

ProductDetail one = obj.array[0];
ProductDetail two = obj.array[1];

And then you can do your manipulation.. also you should probably be using Gson.fromJson() rather than the GsonBuilder


Post a Comment for "No-args Constructor For Class XXX Does Not Exist"