Volley String无法转换为JSONObject

时间:2015-05-12 16:29:35

标签: java android arrays json android-volley

只要我将数组放入Params,我总是会收到以下错误。即使在转换为String之后,它仍然会出现错误。代码工作正常,其中没有contactlist数组。有什么想法吗?

错误

  

com.android.volley.ParseError:org.json.JSONException:创建的值   类型java.lang.String无法转换为JSONObject

示例回复:

{
"username": "test2",
"lists": [
    "contact_0",
    "contact_1",
    "contact_2",
    "contact_3",
    "contact_4",
    "contact_5",
    "contact_6",
    "contact_7",
    "contact_8",
    "contact_9"
]
}

ArrayList<String> contactList = new ArrayList<String>();
public String joinInfo;


Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
        while (phones.moveToNext())
        {
            String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            System.out.println("name : " + name + ", ID : " + phoneNumber);
            joinInfo = name;
            contactList.add(joinInfo);
        }
        phones.close();

 RequestQueue rq = Volley.newRequestQueue(this);

        JSONObject params = new JSONObject();
        try {
            params.put("username", "test2");
            params.put("lists", contactList.toString()); // When i change this to simply "test" a string, it works fine.
            Log.d("PANDA", contactList.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
                "http://postcatcher.in/catchers/55521f03f708be0300001d28", params, //Not null.
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("PANDA", response.toString());
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d("PANDA", "Error: " + error.getMessage());
                Log.d("PANDA", error.toString());
            }
        });

        // Adding request to request queue
        rq.add(jsonObjReq);

1 个答案:

答案 0 :(得分:1)

PostCatcher虽然允许我们发布请求,但它的响应基本上是一个普通字符串“Created”而不是Json格式。因此,我们的客户端代码无法确定它并引发错误。有一件事是,即使没有ArrayList对象,使用plain(String,String)K,V对也会失败。

如果您尝试通过Advanced Rest Client发送请求,则可以验证它(请参阅附件) enter image description here