String无法转换为JSONObject

时间:2014-05-26 22:39:44

标签: android json

在我的应用程序中,我尝试使用填充了所有联系人信息的StringBuffer并使用JSON将其发布到php服务器。

以下是我使用

的代码
public void printBuffer(Context context) {
    StringBuffer output = new StringBuffer();
    output = fetchContacts(context);
//  Log.i("MyMessage", output.toString());
    sendContacts(output);
}

private void sendContacts(StringBuffer sb) {
    try {
        JSONObject toSend = new JSONObject(sb.toString());

        JSONTransmitter transmitter = new JSONTransmitter();
        transmitter.execute(new JSONObject[] {toSend});


    } catch (JSONException e) {
        e.printStackTrace();
    }   
}

由于某些原因,当代码执行并且我想在LogCat中从服务器获得响应时,我看到以下警告:

05-26 01:55:40.383: W/System.err(22683): org.json.JSONException: Value First of type java.lang.String cannot be converted to JSONObject
05-26 01:55:40.393: W/System.err(22683):    at org.json.JSON.typeMismatch(JSON.java:111)
05-26 01:55:40.393: W/System.err(22683):    at org.json.JSONObject.<init>(JSONObject.java:158)
05-26 01:55:40.393: W/System.err(22683):    at org.json.JSONObject.<init>(JSONObject.java:171)
05-26 01:55:40.393: W/System.err(22683):    at com.remoteware.gcm.Contact.sendContacts(Contact.java:28)

有谁知道这个错误意味着什么/我该如何修复它?

这是我的JSONTransmitter类,仅供参考:

public class JSONTransmitter extends AsyncTask<JSONObject, JSONObject, JSONObject> {


String url = "http://myphpserver/json.php";

@Override
protected JSONObject doInBackground(JSONObject... data) {                
    JSONObject json = data[0];
    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);

    JSONObject jsonResponse = null;
    HttpPost post = new HttpPost(url);
    try {
        StringEntity se = new StringEntity("json="+json.toString());
        post.addHeader("content-type", "application/x-www-form-urlencoded");
        post.setEntity(se);

        HttpResponse response;
        response = client.execute(post);
        String resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());
        Log.i("Server response: ", resFromServer);
        jsonResponse=new JSONObject(resFromServer);
        Log.i("Response from server", jsonResponse.getString("msg"));
    } catch (Exception e) { e.printStackTrace();}

    return jsonResponse;
}


}

0 个答案:

没有答案