Emma Emma - 6 months ago 78
Android Question

Fetching json object and array from retrofit

I want to fetch json from [this link][1]: https://api.myjson.com/bins/38ln5 using retrofit

sample json is

{
"students": [
{
"id": "1",
"name": "Larzobispa"
},
{
"id": "2",
"name": "La Cibeles"
}
]
}


Please explain details how to do that.
Thanks a lot, guys!

Answer

Retrofit will automatically parse JSON Object as well JSON Array.

@GET("/register?email=example@123.com")
public void responseString(Callback<Student> response);

your model class looks like:

public class Student{
private ArrayList<StudentInfo> studentList = new ArrayList<>();
     //getter and setters
}

public class StudentInfo{
    private String id;
    private String name;
    //getters and setters
}

Then in response:

@Override
public void onResponse(Response<Student> response, Retrofit retrofit) {
    if (response.isSuccess()) {
        Student student = response.body;
        Log.e("Student name", student.getStudent().get(0).getName()); // do whatever you want
    }else{
        // get response.errorBody()
    }
}
Comments