2012-12-13 109 views
6

當前Facebook API v3.0.2.b將返回一個包含響應的com.facebook.Response對象。你知道如何解析這個嗎?下面的代碼將引發異常:(處理Android Facebook API的響應對象

//execute the request 
Request request = new Request 
(
    session, 
    "/fql", 
    params, 
    HttpMethod.GET, 
    new Request.Callback() 
    { 
     @Override 
     public void onCompleted(Response response) 
     { 
      try 
      { 
       JSONArray json = new JSONArray(response.toString()); 
      } 
      catch (Throwable t) 
      { 
       System.err.println(t); 
      } 
     } 
    } 
); 
Request.executeBatchAsync(request); 

錯誤消息說:

org.json.JSONException: Unterminated object at character 25 of {Response: responseCode: 200, graphObject: GraphObject{graphObjectClass=GraphObject, state={"data":[{"pic_square":..... 

有誰知道什麼是正確的解決方案,我用普通

GraphObject go = response.getGraphObject(); 

..怎麼能我得到GraphUser對象?

對不起,這似乎是一個微不足道的問題,但處理響應對象在facebook文檔中記錄得很差,我無法在網絡上收到任何有關此事的信息:(

非常感謝您提前!

問候克里斯托弗

+0

嘗試看看在response.responseCode'的'價值你的' onCompleted'方法。你能看到200嗎? –

+0

Hi Pratik, 感謝您的回覆。是的 - 代碼是200,同時,我已經解決了這個問題:)我想發佈我的解決方案,但我無法回答自己的問題:( –

+0

很好,你解決了你的問題。我認爲你會得到因此不需要像這樣的'response.toString()'這樣的字符串轉換,這就是我想用'response.responseCode'檢查的結果 –

回答

31

這是對我工作的解決方案 - 我不得不調查的響應和周圍的一些方法有點玩,但總算解決了吧:)

/************************************************************************ 
* Parses the user data from the facebook FQL 
* 
* "SELECT uid, name, pic_square FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())" 
* 
* This is the example query from 
* {@link http://developers.facebook.com/docs/howtos/androidsdk/3.0/run-fql-queries/} 
* 
* @param response The facebook response from the FQL 
************************************************************************/ 
public static final void parseUserFromFQLResponse(Response response) 
{ 
    try 
    { 
     GraphObject go = response.getGraphObject(); 
     JSONObject jso = go.getInnerJSONObject(); 
     JSONArray arr = jso.getJSONArray("data"); 

     for (int i = 0; i < (arr.length()); i++) 
     { 
      JSONObject json_obj = arr.getJSONObject(i); 

      String id  = json_obj.getString("uid"   ); 
      String name = json_obj.getString("name"   ); 
      String urlImg = json_obj.getString("pic_square" ); 

      //... 

     } 
    } 
    catch (Throwable t) 
    { 
     t.printStackTrace(); 
    } 
} 

希望這有助於任何人有一天。

問候

克里斯托弗

UPDATE

GraphObject不再是一個階級,所以才:

JSONObject jso = response.getJSONObject(); 
JSONArray arr = jso.getJSONArray("data");