2013-02-05 45 views
0

我有一個JSON輸出返回是這樣的:如何解析Android中沒有標題對象的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" 
} 
] 

我所熟悉的有標題的對象解析JSON,但我不懂得如何,因爲它是缺少分析上面的JSON線索標題對象。你能否給我提供一些提示/例子,以便我可以檢查它們並解析上述代碼?

注意:我在這裏查了一個類似的例子,但它沒有一個令人滿意的解決方案。

+1

我真的不知道你所說的「有標題目標」的意思。你的意思是JSON在哪裏數組只是一個對象的屬性,而不是整個事物? –

+0

我的意思是,我熟悉解析JSON,如{「webInfo」:[ { 「title」:「facebook」, 「description」:「社交網站」, 「url」:「http: //www.facebook.com「 }, { 」title「:」WoW「, 」description「:」遊戲「, 」url「:」http://us.battle.net/wow/「 }]}但正如你可以在我的JSON輸出中看到的,我沒有標題節點「webinfo」。 – ark

回答

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:社交網站
WoW:遊戲
google:搜索引擎

編輯以添加:由於JSON是一組事物,因此需要使用TypeToken以獲得List,因爲涉及泛型。其實你可以做以下離不開它:

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

你現在有你WebsiteInfo對象從一行代碼的數組。這就是說,使用一個通用的CollectionList如所演示的那樣更加靈活並且通常被推薦。

你可以閱讀更多有關此內容的Gson users guide

+0

謝謝!在你的幫助下,我得到了它的工作。 – ark

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"; 
    } 

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

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