当我对我的Web服务器进行GET api调用时,我得到以下响应。它正在返回值列表。我想遍历每个值并转换为Java对象“ Student”
[{ "name": "xyz", "id": "1234" }, { "name": "abc", "id": "1254" }]
如何将列表中的每个值转换为具有两个字段“名称”和“ id”的java对象。
例如:-
class Student{
String name;
String id;
}
答案 0 :(得分:0)
您可以使用Gson。它解析对给定(兼容)Java对象的Json响应:
GsonBuilder builder = new GsonBuilder();
jsonObject = builder.create().fromJson(jsonString, jsonObject.class);
class jsonObject {
ArrayList<Student> students;
class Student {
String name;
String id;
}
}
jsonString
是您的API响应。由于响应是学生对象的列表,因此您需要将学生对象包装到类似这样的列表中。
答案 1 :(得分:0)
在获得Api响应的地方添加此代码
//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());
}