android - 专门使用 GraphQl 解析 JSON 数据

标签 android json parsing retrofit graphql

我正在尝试使用改造来解析 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"
      }
    }
  ]
}

}

最佳答案

首先,您需要一个 POJO(普通旧 Java 类),它具有您在 JSON 响应中期望的结构。我们称它为 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 解析为事件对象列表:

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 .

关于android - 专门使用 GraphQl 解析 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42573336/

相关文章:

android - 将一个元素添加到回收站 View 时,FAB 与 AppBarLayout 对齐

javascript - 从多个 JSON 文件、Javascript、AJAX 进行实时搜索

java - StAX XML 解析器未转义单引号 (')

c - 如何从单独的函数解析命令行参数

java - 如何解决解析问题?

android - 文本在线性布局的 edittext 内滚动,在 android 的 ScrollView 中

java - 我如何从 fragment 打开新布局并返回 fragment

安卓 : Right place to keep logic for view visibility

javascript - 使用 javascript 将 JSON 对象转换为 XML

java - 如何在 Java Response 对象中返回 JsonArray