【问题标题】:Please, please help me.. I am working on a project and I am getting data from web-services in JSON format [duplicate]拜托,请帮助我..我正在做一个项目,我正在以 JSON 格式从 Web 服务获取数据 [重复]
【发布时间】:2019-05-14 08:01:07
【问题描述】:

json values in toast type在我的项目中从服务器端获取数据,因为我正在发送带有嵌套数组的数组作为响应。在这张图片中,您可以看到带有数组的“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();

请帮帮忙

【问题讨论】:

  • 开始修正标题,让它变得有意义。 “请帮助”不是:这一切都是为了获得帮助。
  • 请正确格式化代码...

标签: java android arrays json


【解决方案1】:

前两行没问题

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

【讨论】:

  • 非常感谢..它工作得很好兄弟
  • 然后别忘了接受答案
猜你喜欢
  • 2023-02-02
  • 2021-11-09
  • 2021-09-16
  • 1970-01-01
  • 2012-03-26
  • 1970-01-01
  • 2021-07-26
  • 2014-04-29
  • 1970-01-01
相关资源
最近更新 更多