2013-07-01 82 views
-2

我正在開發一個Android應用程序,使用Springframework Android休息客戶端連接Facebook。解析一個JSON對象值(一個數組),而不是對象

有了這個網址:

https://graph.facebook.com/me/friends?access_token=AUTH_TOKEN 

Facebook的API返回:

{ 
    "data": [ 
     { 
     "name": "Friend1", 
     "id": "123456" 
     } 
    ] 
} 

我想解析data[]值,作爲數組:

[ 
    { 
     "name": "Friend1", 
     "id": "123456" 
    } 
] 

,並獲得FacebookFriend[]

我該怎麼做GSON

+0

再次downvoting,不說爲什麼。非常具有啓發性。 – VansFannel

回答

2

首先,你需要一個FacebookFriend類(使用公共領域,爲簡單起見,沒有干將):

public class FacebookFriend { 
    public String name; 
    public String id; 
} 

如果你創建了一個包裝類,如:

public class JsonResponse { 
    public List<FacebookFriend> data; 
} 

生活變得簡單得多,你可以簡單地做:

JsonResponse resp = new Gson().fromJson(myJsonString, JsonResponse.class); 

並且完成它。

如果你不想創建一個data場的外圍類,你會使用GSON解析JSON,然後提取該數組:

JsonParser p = new JsonParser(); 
JsonElement e = p.parse(myJsonString); 
JsonObject obj = e.getAsJsonObject(); 
JsonArray ja = obj.get("data").getAsJsonArray(); 

(你可以明顯鏈中的所有這些方法,但我在這個演示中明確表示)

現在,您可以使用Gson直接映射到您的班級。

FacebookFriend[] friendArray = new Gson().fromJson(ja, FacebookFriend[].class); 

儘管如此,但說實話,最好使用一個Collection代替:

Type type = new TypeToken<Collection<FacebookFriend>>(){}.getType(); 
Collection<FacebookFriend> friendCollection = new Gson().fromJson(ja, type); 
1

看來,你的數組包含對象。

你可以用下面的方法解析它。

JsonArray array = jsonObj.get("data").getAsJsonArray(); 
    String[] friendList = new String[array.size()]; 
    // or if you want JsonArray then 
    JsonArray friendArray = new JsonArray(); 
    for(int i=0 ; i<array.size(); i++){ 
     JsonObject obj = array.get(i).getAsJsonObject(); 
     String name = obj.get("name").getAsString(); 
      friendList[i] = name; 
      // or if you want JSONArray use it. 
      friendArray.add(new JsonPrimitive(name)); 

    } 
+0

感謝您的回答。我用更多的細節改變了我的問題。 – VansFannel

+0

我不明白你的觀點。如果我沒有錯,你想添加數據[]值到另一個數組? –

+0

我想獲取data []值,並將它們解析爲一個數組。我再次更新了我的問題。 – VansFannel

相關問題