Question

Class:

public class MyList {

    public int type;
    public String text;
    public boolean[] arr;

    public MyList(int type, String text) {
        this.type = type;
        this.text = text;
        switch (type) {
        case 0:
            arr = new boolean[5];
            break;
        case 1:
            arr = new boolean[10];
            break;
        }
    }
}

JSON Data:

{ "list": [ { "type": 0, "text": "Text 1" }, { "type": 1, "question": "Text 2" } ] }

Parser:

ArrayList<MyList> getList(){
    Gson gson = new Gson();
    MyListsArray mLists = gson.fromJson(bufferString, MyListsArray.class);
    return mLists.list;
}

Class to hold the list items:

public class MyListsArray {
    public ArrayList<MyList> list;
}

Everything goes fine, I get proper values for type and text which are present in the JSON String. But the arr remains null.

Was it helpful?

Solution 2

You can initiate data which is not present in the Json string as below write CustomDeserializer

class CustomDeserializer implements JsonDeserializer<List<MyList>> {

    @Override
    public List<MyList> deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException {

       JsonArray jsonArray =    jsonElement.getAsJsonObject().getAsJsonArray("list");

       List<MyList>  list=new ArrayList<>(30);
       Gson gson = new Gson();

       for (JsonElement element : jsonArray) {

                MyList ob =  gson.fromJson(element,  MyList.class);
                switch (Integer.valueOf(ob.type)) {
                case 0:
                    ob.arr = new boolean[5];
                    break;
                case 1:
                    ob.arr = new boolean[10];
                    break;
                }

               list.add(ob);
        }

        return list;
    }

Finally parse it

 Type typeOf = new TypeToken   <List<MyList>>(){}.getType();
 Gson gson = new GsonBuilder().registerTypeAdapter(typeOf, new CustomDeserializer()).create();
 List<MyList> list = gson.fromJson(builder.toString(),typeOf);

Gson documentation says, if your class doesn't have an no-args constructor and you have not registered any InstanceCreater objects, then it will create an ObjectConstructor (which constructs your Object) with an UnsafeAllocator which uses Reflection to get the allocateInstance method of the class sun.misc.Unsafe to create your class' instance.

If you do have a no-args constructor, Gson will use an ObjectConstructor which uses that default Constructor by calling

yourClassType.getDeclaredConstructor(); // ie. empty, no-args

OTHER TIPS

GSon never calls a constructor of a MyList class in your code. That's why arr gets the default value. Which is null.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top