0

When i make a GET api call to my web server i get below response. It is returning a list of values. I want traverse each value and convert to java object "Student"

[{
        "name": "xyz",
        "id": "1234"
    },
    {
        "name": "abc",
        "id": "1254"
}]

How do i convert each value in the list to java object which has two fields "name" and "id".

Eg:-

class Student{

        String name;
        String id;

    }
user1
  • 45
  • 7
  • 1
    Possible duplicate of [How to convert the following json string to java object?](https://stackoverflow.com/questions/10308452/how-to-convert-the-following-json-string-to-java-object) – ernest_k Sep 08 '18 at 12:35
  • I want to use jackson ObjectMapper. I am not getting how to convert the list to Java object and then each value to Student class. – user1 Sep 08 '18 at 12:56
  • `objectMapper.readValue(jsonString, new TypeReference>(){})` should do – ernest_k Sep 08 '18 at 12:59
  • Thank you @ernest_k. This solution worked. – user1 Sep 08 '18 at 13:08

2 Answers2

0

You could use Gson. It parses the Json response to a given (compatible) Java Object:

GsonBuilder builder = new GsonBuilder();
jsonObject = builder.create().fromJson(jsonString, jsonObject.class);

class jsonObject {
    ArrayList<Student> students;

    class Student {
        String name;
        String id;
    }
}

jsonString would be your API response. Since the response is a list of student objects you will need to wrap the student objects in to something list like.

TheDude
  • 168
  • 10
0

add this code where you get Api response

//make both string id and name public in your Student class
ArrayList<Student> students;
try{
 Student student=new Student();
 JSONObject jsonObject = new JSONObject(response);//adding all response in JSON
students=new ArrayList<>();
 //the loop will run as many times as the object in the response.In this case loop will run two times
 for(i=0;i<jsonObjest.length;i++){
     JSONObject jsonString = jsonObjest.getJSONObject(i);//here getting all object by index 
     //adding data 
     student.id=jsonString.getString("id");
     student.name=jsonString.getString("name");
     students.add(student);//adding all data in arraylist.Now if you want to diplay this all data by listView...You new need to just pass this "students" ArrayList in your adapter 
 }  

}catch(JSONException e) {
  Log.d("===",""Exception::  "+e.getMassege());

}
pratik vekariya
  • 1,105
  • 1
  • 8
  • 14