如何在Android中解析没有title对象的JSON?

时间:2013-02-05 12:40:55

标签: android json gson

我有一个json输出,它返回如下内容:

[
 {
  "title":"facebook",
  "description":"social networking website",
  "url":"http://www.facebook.com"
 },
 {
  "title":"WoW",
  "description":"game",
  "url":"http://us.battle.net/wow/"
 },
 {
  "title":"google",
  "description":"search engine",
  "url":"http://www.google.com"
 }
]

我熟悉解析具有title对象的json,但我不知道如何解析上面的json,因为它缺少title对象。能否请您提供一些提示/示例,以便我可以检查它们并解析上面的代码?

注意:我在这里检查了一个类似的例子,但它没有一个令人满意的解决方案。

4 个答案:

答案 0 :(得分:1)

使用JSONObject.has(String name)检查当前json中是否存在关键名称,例如

 JSONArray jsonArray = new JSONArray("json String");
 for(int i = 0 ; i < jsonArray.length() ; i++) {
   JSONObject jsonobj = jsonArray.getJSONObject(i);
   String title ="";
   if(jsonobj.has("title")){ // check if title exist in JSONObject

     String title = jsonobj.getString("title");  // get title
   }
   else{
        title="default value here";
    }

}

答案 1 :(得分:1)

JSONArray jsonArr = new JSONArray(jsonResponse);

for(int i=0;i<jsonArr.length();i++){ 
JSONObject e = jsonArr.getJSONObject(i);
String title = e.getString("title");
}

答案 2 :(得分:1)

您的JSON是一个对象数组。

围绕Gson(和其他JSON序列化/反序列化)库的整个想法是最终结束自己的POJO。

以下是如何创建一个POJO来表示数组中包含的对象,并从该JSON中获取List个对象:

public class App 
{
    public static void main( String[] args ) 
    {
        String json = "[{\"title\":\"facebook\",\"description\":\"social networking website\"," +
            "\"url\":\"http://www.facebook.com\"},{\"title\":\"WoW\",\"description\":\"game\"," +
            "\"url\":\"http://us.battle.net/wow/\"},{\"title\":\"google\",\"description\":\"search engine\"," +
            "\"url\":\"http://www.google.com\"}]";

        // The next 3 lines are all that is required to parse your JSON 
        // into a List of your POJO
        Gson gson = new Gson();
        Type type = new TypeToken<List<WebsiteInfo>>(){}.getType();
        List<WebsiteInfo> list = gson.fromJson(json, type);

        // Show that you have the contents as expected.
        for (WebsiteInfo i : list)
        {
            System.out.println(i.title + " : " + i.description);
        }
    }
}

// Simple POJO just for demonstration. Normally
// these would be private with getters/setters 
class WebsiteInfo 
{
    String title;
    String description;
    String url;
}

输出:

  facebook:社交网站
  魔兽世界:游戏
  谷歌:搜索引擎

编辑以添加:由于JSON是一系列事物,因此需要使用TypeToken才能访问List,因为涉及泛型。没有它,你实际上可以做到以下几点:

WebsiteInfo[] array = new Gson().fromJson(json, WebsiteInfo[].class); 

现在,您可以从一行代码中获得WebsiteInfo个对象的数组。话虽如此,使用通用的CollectionList进行演示更为灵活,通常建议使用。

您可以在Gson users guide

中详细了解相关信息

答案 3 :(得分:0)

JSONArray array = new JSONArray(yourJson);
for(int i = 0 ; i < array.lengh(); i++) {
JSONObject product = (JSONObject) array.get(i);
    .....
}