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