-2

I am having problem parsing JSON in my model.class I am creating an android app that will request for the user to input the username and password and after clicking the button it will now send a POST request and the request will response with a JSON data.

Here is my request in android studio:

//StudentInfo or Login
    client.post("<url here>", params, new AsyncHttpResponseHandler() {

        @Override
        public void onSuccess(String response) {
            try{
                    StudentModel sm = new StudentModel(obj);
                    sm.retrievalData();
                    flag = true;
                    Toast.makeText(getApplicationContext(), "Redirecting...", Toast.LENGTH_LONG).show();
                    navigatetoProfileActivity();
                }
            }catch(Exception e){
                Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
        }
    });

And here is my StudentModel.class

public void retrievalData(){
//some code to parse the JSON



}

Well, I am a beginner in json parsing and here is the JSON Response.

{
  "info": {
     "add": "<data>",
     "firstName": "<data>",
     "lastName": "<data>",
     "middleName": "<data>",
    }
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Peps
  • 23
  • 5

2 Answers2

3

Well, the most common way of parsing JSONs to Objects in Java is the following:

String json; //the response

Gson gson = new Gson();
Student s = gson.fromJson(json, Student.class);

You need to add dependency of Google/Gson. The above will work in case the JSON you receive in the response is a representation of your Student class.

xenteros
  • 15,586
  • 12
  • 56
  • 91
  • 1
    What specifically is Gson? But I already parsed the JSON using the code above. Thanks for the tips, this might be helpful if I ever encounter GSON. – Peps Sep 30 '16 at 04:38
  • 1
    Gson is the most popular Java JSON parsing library. It has multiple static methods which let you easily parse an Object to a JSON and vise versa. – xenteros Sep 30 '16 at 04:40
0

Well, what you can do in retrievalData() is:

String add = <JSONobjectVariableName>.getJSONObject("info").getString("add");
String firstName = <JSONobjectVariableName>.getJSONObject("info").getString("firstName");

and so on.

Reginald
  • 113
  • 2
  • 10