【问题标题】:org.json.JSONException: Value failure_post of type java.lang.String cannot be converted to JSONObjectorg.json.JSONException:java.lang.String 类型的值 failure_post 无法转换为 JSONObject
【发布时间】:2015-12-07 06:36:35
【问题描述】:

我想用volly library 向服务器发送数据当我用volley library 向服务器发送数据时,出现以下错误:

org.json.JSONException: Value failure_post of type 
                     java.lang.String cannot be converted to JSONObject

这是我的java代码:

public void insertClick(View view)
{
    RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
    HashMap<String, JSONObject> jsonParams = new HashMap<String, JSONObject>();

    JSONObject params = new JSONObject();
    try
    {
        params.put("title","BOOK");
        params.put("intro","hellothere");
    }
    catch (JSONException e)
    {

        Log.i(LABLE, "erorr is : "+ e.getMessage().toString());
    }

    try {

        JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.POST, url,

        new JSONObject(jsonParams),
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Toast.makeText(getApplicationContext() , " insert ok ",Toast.LENGTH_LONG).show();

            }
        },
        new Response.ErrorListener()
        {
            @Override
            public void onErrorResponse(VolleyError error) {
                //   Handle Error

                Log.i(LABLE, "erorr is : "+ error.getMessage().toString());

                Toast.makeText(getApplicationContext() , " insert failed ",Toast.LENGTH_LONG).show();
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/json");

                return headers;
            }
        };
        queue.add(postRequest);
    }
    catch (Exception e)
    {
        Toast.makeText(this , "erorr in Json Object Request ",Toast.LENGTH_LONG).show();
    }

【问题讨论】:

  • 哪里出错了??
  • new JSONObject(jsonParams) 这仅适用于 MAP
  • 而不是new JSONObject(jsonParams),,IMO,您应该只使用paramsnew JSONObject(params),

标签: android json android-volley jsonobject


【解决方案1】:

创建JsonArray

将 jsonObjects 添加到该数组中

然后将完整的JsonObject 创建从JsonArray 发送到JsonObjectRequest

【讨论】:

    【解决方案2】:

    尝试在您的JsonObjectRequest 中输入params 而不是jsonParams,即

    替换这个

    JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.POST, url,new JSONObject(jsonParams),...
    

    JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.POST, url,params,...
    

    或者按如下方式放入地图后从地图中检索

    jsonParams.get("key") 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多