0

In my Android project I'm trying to create a list of MyType using gson. For this I use the following code:

String result = "[{\"text\": \"lala\", \"created\": \"123456\"}, {\"text\": \"lele\", \"created\": \"123456\"}]";

class ReceivedMessage {
    String text;
    String created;
}

List<ReceivedMessage> receivedMessages = new Gson().fromJson(result, new TypeToken<List<ReceivedMessage>>(){}.getType());

for (ReceivedMessage mess : receivedMessages) {
    Log.wtf("This is it", mess.created);
}

Unfortunately I get a nullpointerexception. Does anybody know what I'm doing wrong here?

kramer65
  • 50,427
  • 120
  • 308
  • 488

2 Answers2

1

Defining the class "outside" worked pretty well:

public class ReceivedMessage {
    String text;
    String created;
}

public static void main(String[] args) {
    String result = "[{\"text\": \"lala\", \"created\": \"123456\"}, "
                    +"{\"text\": \"lele\", \"created\": \"123456\"}]";

    List<ReceivedMessage> receivedMessages = new Gson().fromJson(result,
                      new TypeToken<List<ReceivedMessage>>() {}.getType());

    for (ReceivedMessage mess : receivedMessages) {
        System.out.println("This is it " + mess.created);
    }

    ....
}

Note: Gson uses reflection and so it needs access to the class.

Trinimon
  • 13,839
  • 9
  • 44
  • 60
0

Please try this :

Type listType = new TypeToken<ArrayList<ReceivedMessage>>() {}.getType();
List<ReceivedMessage> receivedMessages= new Gson().fromJson(result, listType);

Google Gson - deserialize list<class> object? (generic type)

Community
  • 1
  • 1
Eldhose M Babu
  • 14,382
  • 8
  • 39
  • 44