【问题标题】:Java volley empty json objectJava凌空空json对象
【发布时间】:2023-03-29 07:02:01
【问题描述】:

在响应中,我期望一个 JSON 字符串。 但是现在我必须为要检索的对象提供一个密钥。我想要的响应只是简单的 {"xx":"xx","xx":"xx"} 格式,没有像 {"XX":["xx":"xx"]} 这样的名称的数组。如何在不提供参数的情况下获取 JSON。简而言之,我只想读取我得到的 JSON 响应,而不必提供参数。

protected JSONObject parseJSONMeth() {
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(json);
                users = jsonObject.getJSONArray(JSON_ARRAY);
                JSONObject jo = users.getJSONObject(0);
                return jo;
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return jsonObject;
        }

【问题讨论】:

    标签: java json android-volley


    【解决方案1】:

    你为什么不使用 GSON https://sites.google.com/site/gson/gson-user-guide

    Gson gson = new GsonBuilder().create();
    User result = new User();
    result=(gson.fromJson(json, User .class));
    

    对于用户列表:

    private static List<User> getDataFromJson(String json) {
            Gson gson = new GsonBuilder().create();
            List<User> result = null;
    
            try {
                JSONObject posts=new JSONObject(json);
                result = gson.fromJson(posts.toString(), new TypeToken<List<User>>(){}.getType());
            } catch (JSONException e) {
                e.printStackTrace();
            }
    
            return result;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 2019-07-10
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-22
      相关资源
      最近更新 更多