【问题标题】:Ordered JSON when using Volley (Android)使用 Volley (Android) 时的有序 JSON
【发布时间】:2014-07-22 01:45:12
【问题描述】:

我的网络服务返回了一些 JSON,如下所示:

{
    "error": false,
    "users": [
        {
            "id": "1",
            "username": "user001",
            "level": 10,
            "last_updated": "22072014"
        }

        {
            "id": "2",
            "username": "user002",
            "level": 11,
            "last_updated": "21072014"
        }
    ]
}

我正在为每个用户建立一个长长的项目列表,我只想按照它们列出的顺序将它们显示在屏幕上(so id,然后是用户名、级别、last_updated 等)。

来自这个帖子:JSON order mixed up “一个对象是一组无序的名称/值对” - 我知道 JSONObjects 是无序的映射。有一个建议是使用 LinkedHashMap 来检索有序信息。

我正在使用 Volley 的请求类似于以下:

    JsonObjectRequest jsonReq = new JsonObjectRequest(Method.POST,
            URL, params, new Response.Listener<JSONObject>(){ .. }

是否可以使用 LinkedHashMap 或者有什么方法可以在收到每个用户属性时维护它们的顺序?

【问题讨论】:

    标签: android json


    【解决方案1】:

    databind中尝试ObjectMapper

    fasterxml中可以将json转成对象,包括LinkedHashMap。

    更新: 一年前,当我需要迭代 json 成员时,我发现了这个:Iterate Json data from web service in correct order

    你可以试试这个:

        public <T> T fromJSON(String input, Class<T> clazz) {
        try {
            return mapper.readValue(input != null ? input : "null", clazz);
        } catch (JsonParseException e) {
            throw new RuntimeException(e);
        } catch (JsonMappingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    

    并像这样使用它:

     LinkedHashMap<String, ArrayList> fromJSON = fromJSON(
                    json, LinkedHashMap.class);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-13
      • 1970-01-01
      • 2020-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-04
      相关资源
      最近更新 更多