字符串到jsonObject

时间:2018-05-25 14:10:13

标签: android json android-volley

在下面的代码中,我想使用Response,但它会抛出JSONException

        StringRequest strReq = new StringRequest(Request.Method.POST, REGISTER_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    Log.v(TAG, "Response: " + response);//output {"error":false}

                    try {
                        JSONObject jo = new JSONObject(response); // java.lang.String cannot be converted to JSONObject
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

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

        }
    });

示例JSON字符串:

{
    "error": false,
    "uid": "5b081af13eb974.69226352",
    "user": {
        "name": "66699",
        "created_at": "2018-05-25 18:47:21"
    }
}

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

好吧,要检索response的内容,您在使用JSON请求时无需使用POST。而是做这样的事情:

if (response.equalsIgnoreCase("yourResponseFromTheWebService")) {

    ...
    Toast
} else if (response.equalsIgnoreCase("OtherPossibleResponse")){

    ....
    Toast

} else{

    ....
    Toast      
}

如果是GET请求,您应该执行以下操作:

JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, URL, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        // display response

                        try {

                            //put response into string
                            JSONArray Jresult = response.getJSONArray("user");


                            for (int i = 0; i < Jresult.length(); i++) {
                                JSONObject json_data = Jresult.getJSONObject(i);
                                String lName = json_data.getString("name");
                                String lCreatedAt = json_data.getString("created_at");

//create a model class with your user info like name and created_at and for every user found create a new user object and store its info.
                                _myUser.add(new User(lName, lCreatedAt));
                            }


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

                        Log.d("Response", response.toString());
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d("Error.Response", error.toString());
                    }
                }
        );

        RequestQueue queue = Volley.newRequestQueue(this);
        queue.add(getRequest);