Android Studio中使用Volley解析带XML包裹的API JSON响应
在Android Studio中用Volley解析该响应的步骤
注意:你的API响应是XML包裹的JSON数组,得先提取内部的JSON字符串,再做解析,具体步骤如下:
1. 添加Volley依赖
打开Module级别的build.gradle文件,在dependencies块中添加Volley依赖:
implementation 'com.android.volley:volley:1.2.1'
同步项目确保依赖生效。
2. 创建数据模型类
新建Account.java类,用来存储单条账户数据:
public class Account { private int ActID; private String ActName; private double amount; public Account(int actID, String actName, double amount) { ActID = actID; ActName = actName; this.amount = amount; } // Getter方法,用于获取字段值 public int getActID() { return ActID; } public String getActName() { return ActName; } public double getAmount() { return amount; } }
3. 编写Volley请求与解析逻辑
在Activity或ViewModel中编写请求代码,先获取响应字符串,再提取JSON并解析:
// 初始化Volley请求队列 RequestQueue queue = Volley.newRequestQueue(this); String apiUrl = "你的API接口地址"; // 发起StringRequest请求 StringRequest stringRequest = new StringRequest(Request.Method.GET, apiUrl, response -> { // 第一步:提取XML包裹内的JSON字符串 int startIdx = response.indexOf("["); int endIdx = response.lastIndexOf("]") + 1; String jsonContent = response.substring(startIdx, endIdx); // 第二步:解析JSON数组 try { JSONArray accountArray = new JSONArray(jsonContent); List<Account> accountList = new ArrayList<>(); for (int i = 0; i < accountArray.length(); i++) { JSONObject itemObj = accountArray.getJSONObject(i); int actId = itemObj.getInt("ActID"); String actName = itemObj.getString("ActName"); double amount = itemObj.getDouble("amount"); accountList.add(new Account(actId, actName, amount)); } // 解析完成,这里可以用accountList做后续操作(比如更新UI) } catch (JSONException e) { e.printStackTrace(); // 处理解析异常 } }, error -> { error.printStackTrace(); // 处理请求失败逻辑 }); // 将请求加入队列执行 queue.add(stringRequest);
简化解析的可选方案
如果想简化解析流程,可以使用Gson库:
- 先添加Gson依赖:
implementation 'com.google.code.gson:gson:2.10.1'
- 替换解析部分的代码,直接将JSON字符串转成对象列表:
List<Account> accountList = new Gson().fromJson(jsonContent, new TypeToken<List<Account>>(){}.getType());
内容的提问来源于stack exchange,提问作者kavya
相关产品推荐
相关产品推荐

