如何使用Android Volley for HTTP连接解析另一个JSONObject中的JSONObject

时间:2017-09-23 00:46:54

标签: android json

所以我在阅读android volley中onResponse方法给出的JSON数据时遇到了麻烦,这是我的GET代码。

private void GetSV(){
    final String getURL = "my URL";

    JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, getURL, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
                Iterator keys = response.keys();
                while (keys.hasNext()){
                    Object key = keys.hasNext();
                    switch (key.toString()){
                        case "statusCode":
                            statusCode = getValue(response, "statusCode");
                            break;
                        default:
                            break;
                    }
                    try {
                    JSONObject data = response.getJSONObject("data");
                    Iterator innerKeys = data.keys();
                    while (innerKeys.hasNext()){
                        Object innerKey = innerKeys.hasNext();
                        switch (innerKey.toString()){
                            case "Id":
                                User.setId(getValue(response, "Id"));
                                break;
                            case "firstName":
                                User.setFirstName(getValue(response, "firstName"));
                                break;
                            case "lastName":
                                User.setLastName(getValue(response, "lastName"));
                                User.setName(User.getFirstName() + " " + User.getLastName());
                                name.setText(User.getName());
                                break;
                            case "email":
                                User.setEmail(getValue(response, "email"));
                                break;
                            case "school":
                                User.setCollege(getValue(response, "school"));
                                college.setText(User.getCollege());
                                break;
                            case "fact":
                                User.setRandom_fact(getValue(response, "fact"));
                                random_fact.setText(User.getRandom_fact());
                                break;
                            case "age":
                                User.setAge(getValue(response, "age"));
                                age.setText(User.getAge());
                                break;
                            case "major":
                                User.setMajor(getValue(response, "major"));
                                major.setText(User.getMajor());
                                break;
                            default:
                                break;
                        }
                    }
                }

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

        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            return params;
        }
    };
    RequestQueue requestQueue = Volley.newRequestQueue(context);
    requestQueue.add(getRequest);
}

这就是JSONObject结构在服务器上的样子,这是我想要获取和存储的信息。

{"statusCode":"200","message":"User was found.","data":{"Id":"randomEmail@gmail.com","firstName":"Blah","lastName":"Blah","email":"randomEmail@gmail.com","school":"FSU","fact":"","gender":"male","age":"22","major":"Business Marketing","createdAt":"2017-09-21T22:01:33.000Z","updatedAt":"2017-09-22T18:33:28.000Z"}}

我收到状态代码但我没有收到任何其他字段。这是在另一个JSON解析中进行JSON解析的正确方法吗?如果是这样的最佳方式呢?

2 个答案:

答案 0 :(得分:0)

您可以尝试使用此来源

requestQueue = Volley.newRequestQueue(this);

    JsonObjectRequest obreq = new JsonObjectRequest(Request.Method.GET, JsonURL,
            // The third parameter Listener overrides the method onResponse() and passes
            //JSONObject as a parameter
            new Response.Listener<JSONObject>() {

                // Takes the response from the JSON request
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        if(response.getString("statusCode").equeal("200")) {
                            User user = new User();

                            JSONObject obj = response.getJSONObject("data");

                            user.setId(obj.getString("Id"));
                            user.setFirstName(obj.getString("firstName"));
                            user.setLastName(obj.getString("lastName"));
                            user.setName(obj.getString("firstName")+" "+obj.getString("lastName"));
                            user.setEmail(obj.getString("email"));
                            user.setCollege(obj.getString("school"));
                            user.setRandom_fact(obj.getString("fact"));
                            user.setAge(obj.getString("age"));
                            user.setMajor(obj.getString("major"));

                            name.setText(user.getName());
                            User.setEmail(user.getEmail());
                            college.setText(user.getCollege());
                            random_fact.setText(user.getRandom_fact());
                            age.setText(user.getAge());
                            major.setText(user.getMajor());
                        }


                    }
                    // Try and catch are included to handle any errors due to JSON
                    catch (JSONException e) {
                        // If an error occurs, this prints the error to the log
                        e.printStackTrace();
                    }
                }
            },
            // The final parameter overrides the method onErrorResponse() and passes VolleyError
            //as a parameter
            new Response.ErrorListener() {
                @Override
                // Handles errors that occur due to Volley
                public void onErrorResponse(VolleyError error) {
                    Log.e("Volley", "Error");
                }
            }
    );
    // Adds the JSON object request "obreq" to the request queue
    requestQueue.add(obreq);
}

答案 1 :(得分:0)

使用

Iterator<String> keys = response.keys();  

 insteadof 

Iterator keys = response.keys();

switch (keys.next().toString()) 

insteadof

Object key = keys.hasNext();
                switch (key.toString())

实施例

try {
    Iterator<String> keys = response.keys();
    while (keys.hasNext()) {
        switch (keys.next().toString()) {
            case "statusCode":

                    Toast.makeText(this, "" + response.getString("statusCode"), Toast
                        .LENGTH_SHORT).show();

                break;
            default:
                break;
        }
        JSONObject data = response.getJSONObject("data");
        Iterator<String> innerKeys = data.keys();
        while (innerKeys.hasNext()) {
            switch (innerKeys.next().toString()) {
                case "Id":
                    //User.setId(getValue(response, "Id"));
                    Toast.makeText(this, "" + data.getString("Id"), Toast
                        .LENGTH_SHORT).show();
                    break;
            }
        }
    }
    } catch (JSONException e) {
        Log.e("Error : ", e.getMessage(), e);
    }

}