首页 > 解决方案 > 将返回值列表的 API 响应转换为 JavaObject

问题描述

当我对我的网络服务器进行 GET api 调用时,我得到以下响应。它正在返回一个值列表。我想遍历每个值并转换为 java 对象“学生”

[{
        “名称”:“xyz”,
        “身份证”:“1234”
    },
    {
        “名称”:“abc”,
        “身份证”:“1254”
}]

如何将列表中的每个值转换为具有“名称”和“id”两个字段的 java 对象。

例如:-

class Student{

        String name;
        String id;

    }

标签: javajsonapi

解决方案


在您获得 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());

}

推荐阅读