【问题标题】:How to get 2 json objects at once?如何一次获取 2 个 json 对象?
【发布时间】:2023-03-18 10:06:01
【问题描述】:

我正在使用 volley 来获取 json 对象,我正在获取这样的数据

{“结果用户”:19} {"resultUser2":13}

如何获得第二个(resultuser2)或两者?

try {
    JSONObject o = new JSONObject(response);
    String data = (String) o.get("resultUser2");
    if (!data.equals("")) {
        Toast.makeText(getApplicationContext(), "user2 id" + data, Toast.LENGTH_LONG).show();
        //UserDetailsActivty.this.finish();
    } else {
        Toast.makeText(getApplicationContext(), "Ohh! Sorry,,Signing Up Failed ", Toast.LENGTH_LONG).show();
    }
} catch (JSONException e) {
    e.printStackTrace();
}

【问题讨论】:

  • {"resultUser":19} {"resultUser2":13} 不是有效的 JSON。将它们放入数组或重新设计方案。
  • 制作场景
  • 如果您无法将数据作为有效的 json。您可以尝试使用“}”和一些字符串操作进行拆分,以使您的数据成为有效的 json。但我认为你应该找到一种方法来修复数据的来源
  • 是的,我想到了这个主意
  • 所以网络服务应该只返回一个值或数组?

标签: android json post android-volley


【解决方案1】:

你可以像这样使用 JsonArray 来遍历所有的 jsonobjects

try {

JSONArray jsonArray = new JSONArray(response);

for (int i =0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.get(i);
//do whatever you want to do with the data
}
} catch(Exception e) {

}

【讨论】:

  • 它给了我这个错误“foreach not applicable to type JSONArray”
猜你喜欢
  • 1970-01-01
  • 2014-03-09
  • 2021-11-01
  • 1970-01-01
  • 2016-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多