如果名称不断变化,如何检索JSON对象的值

时间:2019-03-30 17:11:24

标签: android json

我正在MediaWiki API的帮助下获取有关某些动物的一些信息 http://en.wikipedia.org/w/api.php?action=query&prop=extracts&titles=Animal&format=json&exintro=1  但是对象之一是根据动物而变化的页面。如何访问页面对象(其中包含有关动物的摘录)?

这是JSON查询结果

    {  
   "batchcomplete":"",
   "warnings":{  },
   "query":{  
      "pages":{  
         "6598":{  
            "pageid":6598,
            "ns":0,
            "title":"Camel",
            "extract":"<p class=\"mw-empty-elt\">\n</p>\n<p>A <b>camel</b> is 
             an even-toed ungulate in the genus <i>Camelus</i> that bears 
             distinctive fatty deposits known as \"humps\" on its back. 
             Camels have long been domesticated and, as livestock, they 
             provide food (milk and meat) and textiles (fiber and felt from 
             hair). As working animals, camels\u2014which are uniquely suited 
             to their desert habitats\u2014are a vital means of transport for 
             passengers and cargo. There are three surviving species of 
             camel."
         }
      }
   }
}

2 个答案:

答案 0 :(得分:1)

您应该考虑以下几点:

  1. 仅在响应时查找响应状态代码,例如:

    onResponse(){ 如果(statusCode == 200){    // ---现在在这里查找特定于响应的主体  } }

  2. 使用JsonObject作为响应主体的模型,例如:

@Override
public void onResponse(Call < JsonObject > call, Response < JsonObject > response) {
  if (response.code() == 200) {
    if (!response.body().toString().isEmpty()) {
     // ----- Now Here You can Extract the JsonObject Field you are looking for
     // --- Example :
     
     JsonObject object = response.body();
     String target = object.get("field_name);
     
    } else {
      // Empty Response
    }
  } else {
    // Failure or whatever
  }
}

您如何获得此回复?改装,排球,OkHttp ??

每种方法都为更改字段提供了一种简单的解决方法

答案 1 :(得分:1)

如果我没错-JSON中的“提取”值正在更改,如果是这样,只需将其作为String值获取并将其设置为具有特殊标记-html的TextView即可,如下所示:

String  description;
TextView  tv_description;

tv_description = (TextView) findViewById(R.id.btn_desc);

tv_description.setText(Html.fromHtml(description));

在其他情况下,您需要为所有JSON品种创建一个POJO并使用通用方法。