java - 拜托,请帮帮我。我正在做一个项目,我正在从 Web 服务获取 JSON 格式的数据
问题描述
我的项目中 toast 类型的 json 值从服务器端获取数据,因为我正在发送带有嵌套数组的数组作为响应。在这张图片中,您可以看到带有数组的“Secondary_number”有一些值。我需要打印这些值。我附上了我的java代码。当我尝试运行此程序时,我的屏幕变黑了。
JSONObject obj = new JSONObject(response);
JSONArray jsonArray = obj.getJSONArray("response");
service = new String[jsonArray.length()];
//Iterate the jsonArray and print the info of JSONObjects
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i)
//getting second array
JSONArray jArray = jsonObject.getJSONArray("secondary_number");
//Iterate the jsonArray and print the info of JSONObjects
for (int j = 0; j < jArray.length(); j++) {
do some computation
}
service[i] = jsonObject.getString("service_id").toString(); //getting values in response
tv1 = jsonObject.getString("service_id");
tv2 = jsonObject.getString("user_id").toString();
tv3 = jsonObject.getString("username").toString();
tv4 = jsonObject.getString("company_name").toString();
tv5 = jsonObject.getString("assigned_time").toString();
所以请帮忙
解决方案
前两行没问题
JSONObject obj = new JSONObject(response);
JSONArray services = obj.getJSONArray("response");
但在那之后,它不是。我不知道你想做什么,可能是出于调试目的,所以我不会用它做任何事情。另外,我会得到字符串以使其清楚。
for(int i = 0; i < services.length(); i++){
JSONObject service = services.getJSONObject(i);
tv1 = service.getString("service_id");
tv2 = service.getString("assigned_time");
tv3 = service.getString("company_name");
tv4 = service.getString("user_id");
tv5 = service.getString("username");
//for some reason, secondary_number value is escaped which mean
//it is a string that you will have to parse
String secondary_number = service.getString("secondary_number");
JSONArray secondary_number_json = new JSONArray(secondary_number);
for(int j = 0; j < secondary_number_json.length(); j++){
JSONObject secondary = secondary_number_json.getJSONObject(j);
String name = secondary .getString("name");
String alternative_no = secondary .getString("alternative_no");
String designation = secondary .getString("designation");
// do things with those strings
}
}
为了更好地使用数据,您应该查看Gson库以使用 pojo 类更轻松地解析 json