首页 文章

如何在java中用volley解析json

提问于
浏览
-1

现在我必须使用array-data-name在php中创建json,如下所示:

print "{data : ".json_encode($the_data,JSON_UNESCAPED_UNICODE)."}"

在android的java工作室我喜欢这样:

String url = "httpmywebsite";
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,
                        new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject response) {
                                try {
                                    JSONArray jsonArray = response.getJSONArray("data");
                                    for (int i = 0; i < jsonArray.length(); i  ) {
                                        JSONObject respons = jsonArray.getJSONObject(i);
                                        String id = respons.getString("id");
                                        String name = respons.getString("name");
                                        String email = respons.getString("email");

}
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("VOLLEY", "ERROR");
                    }
                }

                );
                requestQueue.add(jsonObjectRequest);
            }

它工作正常,但现在我想更新我的PHP文件

来自:

print "{data : ".json_encode($the_data,JSON_UNESCAPED_UNICODE)."}"

至 ;

print json_encode($the_data,JSON_UNESCAPED_UNICODE)

所以我试图更新我的java代码如下所示,但不工作!

JSONArray jsonArray= new JSONArray(response.toString());

新的PHP代码返回此json:

[{"0":"100","id":"100","1":"sandra","name":"sandra","2":"x@x.com","email":"x@x.com"}]

我已添加此代码以获取齐射的错误类型;

@Override

public void onErrorResponse(VolleyError error){

if (error instanceof TimeoutError || error instanceof NoConnectionError) {
    Toast.makeText(context,
            context.getString(R.string.error_network_timeout),
            Toast.LENGTH_LONG).show();
} else if (error instanceof AuthFailureError) {
    //TODO
} else if (error instanceof ServerError) {
   //TODO
} else if (error instanceof NetworkError) {
  //TODO
} else if (error instanceof ParseError) {
Toast.makeText(context,
            "ParseError",
            Toast.LENGTH_LONG).show();
    }
    }

我收到此消息: ParseError

1 回答

  • 0

    这是PHP的确切输出?

    [{"0":"100","id":"100","1":"sandra","name":"sandra","2":"x@x.com","email":"x@x.com"}]

    因为如果是这种情况你会得到一个错误,因为没有包含它的json数组“data” .

相关问题