如何使用gson从json创建java列表?获得NullPointerException

时间:2013-11-19 18:43:43

标签: java android json nullpointerexception gson

在我的Android项目中,我尝试使用gson创建MyType列表。为此,我使用以下代码:

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);
}

不幸的是我得到了一个nullpointerexception。有谁知道我在这里做错了什么?

2 个答案:

答案 0 :(得分:1)

将课程定义为“外部”非常有效:

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);
    }

    ....
}

注意:Gson使用反射,因此需要访问该类。

答案 1 :(得分:0)

请试试这个:

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

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