user3791111
user3791111

Reputation: 1609

Gson, TypeToken, getting array of objects from JSON, field values are not set

I'm trying to get an array of objects from a JSON string, using Gson and its TypeToken class.

Here is the code I used:

List<MyItem> items = gson.fromJson(jsonString, new TypeToken<ArrayList<MyItem>>() {
 }.getType());

The list of objects is created, it has the expected number of MyItem objects but all their field values are not set (they are null, 0, false, the default values).

Why are those field values not set? Am I missing something?

The JSON string itself is correct, and I get those objects other way (using more verbose code and another library). I'm just trying to write compact code.

Upvotes: 0

Views: 1434

Answers (1)

immobiluser
immobiluser

Reputation: 359

You probably make a mistake confusing various objects. If your objects types didn't correspond, setters are not called.

public class MyObjectA implements Serializable
{
    private MyObjectB myObjectB;
    // with getter and setter
}

public class MyObjectB implements Serializable
{
    private int id;
    // with getter and setter
}

If you serveur return a List<MyObjectA>, the json return will be :

[{
    "myObjectB": {
        "id": 6034
    }
}]

Json array to ArrayList gson, like you have done :

Type collectionType = new TypeToken<ArrayList<MyObjectA>>() {}.getType();
ArrayList<MyObjectA> navigation = gson.fromJson(jsonResponse, collectionType);
for (MyObjectA myObjectA : navigation) {
    System.out.println(myObjectA.getMyObjectB().getId());
}

Confusion objects class, doesn't warn neither doesn't crash, but don't set objets properly collection objects.

Upvotes: 1

Related Questions