【问题标题】:How can I parse following JSON response using GSON如何使用 GSON 解析以下 JSON 响应
【发布时间】:2016-08-04 17:11:50
【问题描述】:

这是来自服务器的 JSON 响应,现在我该如何反序列化它。

{
"posts": [
    {
        "id": "1",
        "fname": "yourFname1",
        "lname": "yourLname1"
    },
    {
        "id": "2",
        "fname": "yourFname2",
        "lname": "yourLname2"
    },        
    {
        "id": "111",
        "fname": "star",
        "lname": "trek"
    },
    {
        "id": "111",
        "fname": "star",
        "lname": "trek"
    }
  ]
}

【问题讨论】:

  • 我认为你没有仔细阅读我的问题。我想使用 gson 解析 json,这不是重复的问题。明白了吗?

标签: android json parsing gson


【解决方案1】:

首先你需要一个 javaBean

public class OuterBean {

    public ArrayList<InnerBean> posts;

    public class InnerBean{

        public String id;
        public String fname;
        public String lname;
    }

}

然后解析json调用parseJson(name of json);

private void parseJson(String result) {
    Gson gson = new Gson();
    OuterBean outerBean = gson.fromJson(result, OuterBean.class);
}

【讨论】:

    【解决方案2】:

    假设您的 JSON 位于 String json

    创建JSONObjectJSONArray的对象来解析JSON内容。

    JSONObject jsonObject = new JSONObject(json);
    JSONArray jsonArray = jsonObject.getJSONArray("posts");
    for(int i = 0; i<jsonArray.length(); i++) {
        JSONObject ob = jsonArray.getJSONObject(i);
        String id = ob.getString("id");
        String fname = ob.getString("fname");
        String lname = ob.getString("lname");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-10
      • 2019-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-10
      • 1970-01-01
      相关资源
      最近更新 更多