如何使用GSON解析这个JSON数据,并将其放入ArrayList中?

4

我正在尝试解析来自MongoDB云服务器的数据。从服务器返回的JSON数据如下:

[
{
    "_id": {
        "$oid": "4e78eb48737d445c00c8826b"
    },
    "message": "cmon",
    "type": 1,
    "loc": {
        "longitude": -75.65530921666667,
        "latitude": 41.407904566666666
    },
    "title": "test"
},
{
    "_id": {
        "$oid": "4e7923cb737d445c00c88289"
    },
    "message": "yo",
    "type": 4,
    "loc": {
        "longitude": -75.65541383333333,
        "latitude": 41.407908883333334
    },
    "title": "wtf"
},
{
    "_id": {
        "$oid": "4e79474f737d445c00c882b2"
    },
    "message": "hxnxjx",
    "type": 4,
    "loc": {
        "longitude": -75.65555572509766,
        "latitude": 41.41263961791992
    },
    "title": "test cell"
}

我遇到的问题是数据结构返回时没有给JSON对象数组命名。每个返回的对象都是一个“post”。但是如果没有JSON对象数组的名称,该如何使用GSON解析它呢?我想将这些“posts”放入一个类型为Post的ArrayList中。

2个回答

13

你正在寻找的代码片段:

String jsonResponse = "bla bla bla";
Type listType = new TypeToken<List<Post>>(){}.getType();
List<Post> posts = (List<Post>) gson.fromJson(jsonResponse, listType);

这应该是被接受的答案。Sam_D的回答是可行的,但是这段代码似乎更快,并且在较大的JSONArrays上可能会更明显。 - Matt
处理大型JSON时确实快得多。 - Patrick Jackson
太棒了!能否解释一下它是如何运作的?第2行和第3行。 - Roman

1
使用JSONArray的构造函数来解析字符串:
//optionally use the com.google.gson.Gson package
Gson gson = new Gson();
ArrayList<Post> yourList = new ArrayList<Post>();
String jsonString = "your string";
JSONArray jsonArray = new JSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++){
  Post post = new Post();

  //manually parse for all 5 fields, here's an example for message
  post.setMessage(jsonArray.get(i).getString("message")); 

  //OR using gson...something like this should work
  //post = gson.fromJson(jsonArray.get(i),Post.class);

  yourList.Add(post);
 }

考虑到只有5个字段,使用Gson可能比你需要的开销更大。


我计划在我的项目继续进行时添加更多的字段。 - IZI_Shadow_IZI

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接