Question

What's the simplest/fastest way to deserialize a single key value element with Gson library on Android? Server sends something like:

{
    "data": [
        {
            "Field1": "Value1",
            "Field2": "Value2",
            "Field3": "Value3"
        },
        {
            "Field1": "Value1",
            "Field2": "Value2",
            "Field3": "Value3"
        }
    ]
}

So I need to "enter" data value (the array) and then bind the values to a model. Ok with the second part, but I'm missing the first. Should I use an HashMap, JsonParser or something?

JsonElement dataElem = new JsonParser().parse(response);

String data = dataElem.getAsJsonObject().get("data").getAsString();

bundle.putParcelableArray("models", gson.fromJson(data, Model[].class));

Am i near the right solution? Many thanks.

Was it helpful?

Solution

Your problem is here:

String data = dataElem.getAsJsonObject().get("data").getAsString();

You don't want a String, you want the actual JsonElement from the parse tree:

JsonElement je = dataElem.getAsJsonObject().get("data");

Then your deserialization to an array of your Model will work:

bundle.putParcelableArray("models", gson.fromJson(je, Model[].class));

OTHER TIPS

In simple way you can parse it as

1. Without Model class

JsonParser jsonParser = new JsonParser();
JsonElement element = jsonParser.parse(Your_JSON_String).getAsJsonObject().get("data");
Type typeOfCollection = new TypeToken<List<Map<String, String>>>(){}.getType();
List<Map<String, String>> dataList = gson.fromJson(element, typeOfCollection);

2. With Model class.

public class Model {
    private List<Map<String,String>> data;
}

 Model model= gson.fromJson(Your_JSON_String, Model.class)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top