java - 将返回值列表的 API 响应转换为 JavaObject
问题描述
当我对我的网络服务器进行 GET api 调用时,我得到以下响应。它正在返回一个值列表。我想遍历每个值并转换为 java 对象“学生”
[{ “名称”:“xyz”, “身份证”:“1234” }, { “名称”:“abc”, “身份证”:“1254” }]
如何将列表中的每个值转换为具有“名称”和“id”两个字段的 java 对象。
例如:-
class Student{
String name;
String id;
}
解决方案
在您获得 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());
}
推荐阅读
- python - python请求输出中的错误编码(?)
- vue.js - 清单:行:1,列:1,语法错误。清单的公共链接已更改
- sql - SQL 参数化排序
- javascript - VSCode 停止连接到 MongoDB 服务器 - NodeJS
- flutter - 我正在尝试制作一个与极客教程作为参考的极客应用程序。我有以下错误
- matplotlib - geopandas 在使用 xlim、ylim 时控制图例大小
- ant-media-server - 一次性游戏代币未获得授权
- javascript - 对具有 htpasswd 的 url 的 Axios GET 请求
- flutter - 在颤动中发送带有地图列表的http补丁请求
- git - 如何使用 Sourcetree 从 git 中卸载中间提交?