我正在连接一个网站及其 api 来检索数据。我下面的代码会执行此操作并获取响应正文,但是如何解析该响应正文?我是否必须创建自己的函数来搜索我想要的术语,然后获取每个术语的子内容?还是已经有一个我可以使用的库可以为我做到这一点?
private class GetResultTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String response = "";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("https://api.bob.com/2.0/shelves/45?client_id=no&whitespace=1");
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(String result) {
apiStatus.setText(result); //setting the result in an EditText
}
}
响应体
{
"id": 415,
"url": "http://bob.com/45/us-state-capitals-flash-cards/",
"title": "U.S. State Capitals",
"created_by": "bub12",
"term_count": 50,
"created_date": 1144296408,
"modified_date": 1363506943,
"has_images": false,
"subjects": [
"unitedstates",
"states",
"geography",
"capitals"
],
"visibility": "public",
"has_access": true,
"description": "List of the U.S. states and their capitals",
"has_discussion": true,
"lang_terms": "en",
"lang_definitions": "en",
"creator": {
"username": "bub12",
"account_type": "plus",
"profile_image": "https://jdfkls.dfsldj.jpg"
},
"terms": [
{
"id": 15407,
"term": "Montgomery",
"definition": "Alabama",
"image": null
},
{
"id": 15455,
"term": "Juneau",
"definition": "Alaska",
"image": null
},
{
"id": 413281851,
"term": "Tallahassee",
"definition": "Florida",
"image": null
},
{
"id": 413281852,
"term": "Atlanta",
"definition": "Georgia",
"image": null
}
]
}