【问题标题】:Parsing JSON data specifically using GraphQl专门使用 GraphQl 解析 JSON 数据
【发布时间】:2017-07-23 05:40:21
【问题描述】:

我正在尝试使用改造来解析 JSON 数据,但我使用 GraphQL 作为我的 API。附件是我试图解析的数据示例。 我尝试按照此链接中的教程进行操作:http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ 但他从中提取的 JSON 数据来自 REST API。

这是 GraphQL 数据:

 {
 "data": {
"allEvents": {
  "edges": [
    {
      "node": {
        "title": "UWB Weekly Meeting"
      }
    },
    {
      "node": {
        "title": "Startup Weekly"
      }
    },
    {
      "node": {
        "title": "Microsoft Capstone Opportunity"
      }
    },
    {
      "node": {
        "title": "UWB Camp Kickoff"
      }
    },
    {
      "node": {
        "title": "Agusto's Winter Event"
      }
    }
  ]
}

} }

【问题讨论】:

  • 发布您的活动代码...
  • 您使用的是什么 API?

标签: android json parsing retrofit graphql


【解决方案1】:

首先,您需要一个具有您在 JSON 响应中所期望的结构的 POJO(普通的旧 Java 类)。我们称之为Event。从您的示例中,它有一个标题,所以这就是我们需要的类:

public class Event {
    private String id;
    private String title;

    public Event() {

    }

    public Event(String id, String title) {
        this.id = id;
        this.title = title;
    }

    @Override
    public String toString() {
        return "Event{" +
                "id='" + id + '\'' +
                ", title='" + title + '\'' +
                '}';
    }

    public String getId() {
      return id;
    }

    public String getTitle() {
        return title;
    }

}

然后可以使用 Gson 库将响应 JSON 解析为 Event 对象列表:

Gson gson = new Gson();
try {
    JSONArray jsonEvents = new JSONObject(body).getJSONObject("data").getJSONObject("allEvents").getJSONArray("edges");
    for (int i = 0; i < jsonEvents.length(); ++i) {
        JSONObject event = jsonEvents.getJSONObject(i).getJSONObject("node");
        Log.v("TAG", gson.fromJson(event.toString(), Event.class).toString());
    }
} catch (JSONException e) {
    e.printStackTrace();
}

你可以找到一个完整的例子here

【讨论】:

  • 嘿伙计,我只想感谢您的帮助。我真的无法用语言来解释,但这真的很有帮助。我们试图让我们的代码运行好几天,而您的建议和代码肯定有帮助。
猜你喜欢
  • 1970-01-01
  • 2021-11-22
  • 1970-01-01
  • 1970-01-01
  • 2020-12-06
  • 1970-01-01
  • 2013-11-15
  • 2022-01-23
  • 2011-07-08
相关资源
最近更新 更多