0

Please could you give me a hand here, I am trying to parse a JSON file from a URL. Below is the code that i used to grab the file and initially just posted it to a TextView but now I want to parse the tags and use them?

private void postData(final String param, final TextView tv) {

    final RequestQueue request = Volley.newRequestQueue(this);

    JSONObject postReq = new JSONObject(Request.Method.GET, url_login, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            System.out.println("Error [" + error + "]");

        }
    }) {

        @Override
        public Map getHeaders() throws AuthFailureError {
            Map headers = new HashMap();
            headers.put("Accept", "application/json");
            System.out.println(headers);
            return headers;
        }
    };
    request.add(postReq);
}

an example of the JSON is below

{
“UserInfo”: {
    “User”: {
        “name”: “Craig”,
        “surname”: "Churchill",
        "userId": "1463353",
        "userAlias": "Craig"
    }
  }
}

I have tried this but have just failed constantly and just cannot get it right.

enter image description here

Community
  • 1
  • 1
Stillie
  • 2,647
  • 6
  • 28
  • 50

1 Answers1

0
{
    "UserInfo": {
        "User": {
            "name": "Craig",
            "surname": "Churchill",
            "userId": "1463353",
            "userAlias": "Craig"
        }
    }
}

It´s a valid json. I´ve tried it on http://jsonlint.com/ But you've got some double commas that have a weird encoding. I put the json above with a right doble comma enconding, since jsonlint was giving errors validating the json until I changed them.

The problem might be on how you're accesing the object and it´s childrens. Try this way.

@Override
public void onResponse(JSONObject response) {
    try {
        JSONObject userObj = response.getJSONObject("UserInfo")
                            .getJSONObject("User");
        String name = userObj.getString("name");
        ...
    } catch (JSONException jsEx) {
        jsEx.printStackTrace();
    }

}
reixa
  • 6,903
  • 6
  • 49
  • 68