0

我正在使用带有 Eclipse 的 Facebook SDK 向朋友发送请求,我想在“数据”字段中包含应用程序的其他信息。我不断收到错误 java.lang.String 无法转换为 JSON 对象,无论我尝试什么。我尝试在 JSONArray 中检索数据并在 JSONObjects 中检索特定值,但无济于事。如果您能告诉我我做错了什么,我将不胜感激。

我在下面包含了相关代码。令人敬畏的徽章和社会业力值是占位符,从此处的 facebook 教程复制:https ://developers.facebook.com/docs/android/send-requests

请求发送代码,直接来自示例(除了消息字段):

    private void sendRequestDialog() {
    Bundle params = new Bundle();
    params.putString("title", "Send a Request");
    params.putString("message",
            application.getUserId()+" has invited you to an event!"); 
    String idHolder = ids.get(0);
    for (int i = 1; i < ids.size(); i++) 
    {
        idHolder = idHolder+"," + ids.get(i); // a for-loop to get all selected
                                            // user ids in the recipients
                                            // list (starting at 1 to
                                            // prevent comma placement
                                            // issues)
    }
    params.putString("to", idHolder); // comma seperated list of facebook
                                        // IDs to preset the recipients.
    params.putString("data",
            "{\"badge_of_awesomeness\":\"1\"," +
            "\"social_karma\":\"5\"}");

    WebDialog requestsDialog = ( // initializes a web dialog, sends the
                                    // requests parameters to the stored
                                    // IDs, displays errors in sending
    new WebDialog.RequestsDialogBuilder(this, Session.getActiveSession(),
            params)).setOnCompleteListener(new OnCompleteListener() {

        @Override
        public void onComplete(Bundle values, FacebookException error) {
            if (error != null) {
                if (error instanceof FacebookOperationCanceledException) {
                    Toast.makeText(getApplicationContext(),
                            "Request cancelled", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(),
                            "Network Error", Toast.LENGTH_SHORT).show();
                }
            } else {
                final String requestId = values.getString("request");
                if (requestId != null) {
                    Toast.makeText(getApplicationContext(), "Request sent",
                            Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(),
                            "Request cancelled", Toast.LENGTH_SHORT).show();
                }
            }
        }

    }).build();
    requestsDialog.show();
}

其次是接收端的代码(Toast(badge_of_awesomeness) 用于测试目的):

    private void getRequestData(final String inRequestId) {
        // Create a new request for an HTTP GET with the
        // request ID as the Graph path.
        Request request = new Request(Session.getActiveSession(), 
                inRequestId, null, HttpMethod.GET, new Request.Callback() {

                    @SuppressLint("NewApi") @Override
                    public void onCompleted(Response response) {
                        // Process the returned response
                        GraphObject graphObject = response.getGraphObject();
                        FacebookRequestError error = response.getError();
                        // Default message
                        String message = "Incoming request";
                        if (graphObject != null) {
                            // Check if there is extra data
                            if (graphObject.getProperty("data") != null) {
                                try {
                                    // Get the data, parse info to get the key/value info

                                    JSONObject dataObject = 
                                            new JSONObject((String)graphObject.getProperty("data"));

       Toast.makeText(getApplicationContext(), dataObject.getString("badge_of_awesomeness"), 500).show();
                                   // new JSONObject((String)graphObject.getProperty("data"));
                                    // Get the value for the key - badge_of_awesomeness
                                    String badge = 
                                        dataObject.getString("badge_of_awesomeness");
                                    // Get the value for the key - social_karma
                                    String karma = 
                                        dataObject.getString("social_karma");
                                    // Get the sender's name
                                    JSONObject fromObject = 
                                        (JSONObject) graphObject.getProperty("from");
                                    String sender = fromObject.getString("name");
                                    String title = sender+" sent you a gift";
                                    // Create the text for the alert based on the sender
                                    // and the data
                                    message = title + "\n\n" + 
                                        "Badge: " + badge + 
                                        " Karma: " + karma;
                                } catch (JSONException e) {
                                    message = "Error getting request infoJSON";
                                    Log.e("!", "!", e);
                                }
                            } else if (error != null) {
                                message = "Error getting request info";
                            }
                        }
                        Toast.makeText(getApplicationContext(),
                                message,
                                Toast.LENGTH_LONG).show();
                    }
            });
        // Execute the request asynchronously.
        Request.executeBatchAsync(request);
    }

JSON:

    {
      "id": "493703870648580", 
      "application": {
      "name": "Send Requests How To", 
      "id": "403223126407920"
    }, 
      "to": {
      "name": "Chris Abe Colm", 
      "id": "100003086810435"
    }, 
      "from": {
      "name": "Christine Abernathy", 
      "id": "1424840234"
    }, 
      "data": "{\"badge_of_awesomeness\":\"1\",\"social_karma\":\"5\"}", 
      "message": "Learn how to make your Android apps social", 
      "created_time": "2012-10-07T17:29:57+0000"
    }

日志猫:

    06-20 17:33:47.413: E/!(31515): !
    06-20 17:33:47.413: E/!(31515): org.json.JSONException: Value         nullandroid.widget.EditText@4164a490android.widget.EditText@414d9928 of type         java.lang.String cannot be converted to JSONObject
    06-20 17:33:47.413: E/!(31515):     at org.json.JSON.typeMismatch(JSON.java:111)
    06-20 17:33:47.413: E/!(31515):     at org.json.JSONObject.<init>(JSONObject.java:159)
    06-20 17:33:47.413: E/!(31515):     at org.json.JSONObject.<init>(JSONObject.java:172)
    06-20 17:33:47.413: E/!(31515):     at hro.informatica.gameplanner.GamePlannerMain$10.onCompleted(GamePlannerMain.java:482)
    06-20 17:33:47.413: E/!(31515):     at com.facebook.Request$4.run(Request.java:1725)
    06-20 17:33:47.413: E/!(31515):     at android.os.Handler.handleCallback(Handler.java:733)
    06-20 17:33:47.413: E/!(31515):     at android.os.Handler.dispatchMessage(Handler.java:95)
    06-20 17:33:47.413: E/!(31515):     at android.os.Looper.loop(Looper.java:212)
    06-20 17:33:47.413: E/!(31515):     at android.app.ActivityThread.main(ActivityThread.java:5151)
    06-20 17:33:47.413: E/!(31515):     at java.lang.reflect.Method.invokeNative(Native Method)
    06-20 17:33:47.413: E/!(31515):     at java.lang.reflect.Method.invoke(Method.java:515)
    06-20 17:33:47.413: E/!(31515):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
    06-20 17:33:47.413: E/!(31515):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
    06-20 17:33:47.413: E/!(31515):     at dalvik.system.NativeStart.main(Native Method)
    06-20 17:33:47.423: W/ResourceType(31515): CREATING STRING CACHE OF 44 bytes

我真的不明白我在这里做错了什么,我花了一整天(嗯,整个下午)倾注于 stackoverflow 尝试不同的解决方案。我可能在某个地方犯了一个明显的错误,但我找不到它。我真的卡住了,请帮帮我!

4

1 回答 1

0

1.您知道您在哪条特定线路上收到异常吗?

在您的接收端代码中,我看到您尝试以两种不同的方式获取 JSON:

JSONObject dataObject = new JSONObject((String)graphObject.getProperty("data"));
...
JSONObject fromObject = (JSONObject) graphObject.getProperty("from");

第一个是将String转换为JSON的正确方法,第二个不是。

你能试试:

JSONObject fromObject = new JSONObject((String)graphObject.getProperty("from"));

代替:

JSONObject fromObject = (JSONObject) graphObject.getProperty("from");


2.也在你的发送端代码上:我看不到你会打电话的任何地方:

params.putString("from", "{...json stuff...}");

实际上把“从”放在任何地方。也许你忘了包括那个?

于 2014-06-20T19:13:58.580 回答