【问题标题】:How to parse this JSON data using GSON? and put it into an ArrayList如何使用 GSON 解析这个 JSON 数据?并将其放入 ArrayList
【发布时间】:2011-10-04 19:28:03
【问题描述】:

我正在尝试解析来自 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 对象数组的名称。返回的每个对象都是一个“帖子”。但是,如果 JSON 对象数组没有名称,我如何使用 GSON 解析它。我想将这些“帖子”放入 Post 类型的 ArrayList 中。

【问题讨论】:

    标签: android json parsing mongodb gson


    【解决方案1】:

    您正在寻找的代码段:

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

    【讨论】:

    • 这应该是公认的答案。 Sam_D 的答案有效,但此代码似乎要快得多,并且在较大的 JSONArrays 上可能会很明显。
    • 是的,处理大型 json 时要快得多
    • 太棒了!你能解释一下它是如何工作的吗?第 2 行和第 3 行
    【解决方案2】:

    使用 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 可能会比您需要的开销更大。

    【讨论】:

    • 好吧,随着项目的继续,我确实计划添加更多字段
    猜你喜欢
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2020-11-09
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    相关资源
    最近更新 更多