0

I have some JSON returned from my web-service like below:

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

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

I'm building up a long list of items for each user and I want just display them to the screen in the order that they are listed (so id, then username, level, last_updated, etc).

From this post: JSON order mixed up "An object is an unordered set of name/value pairs" - I understand that JSONObjects are unordered maps. There is a suggestion of using LinkedHashMap to retrieve the ordered information.

I'm using Volley with a request similar to below:

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

Is it possible to use the LinkedHashMap or is there any way of maintaining the order of each users attributes as they are received?

Community
  • 1
  • 1
user3217789
  • 211
  • 1
  • 3
  • 11

1 Answers1

0

Try ObjectMapper in databind

in fasterxml, it can convert json to object including LinkedHashMap.

update: a year ago i found this when I needed to iterate json members: Iterate Json data from web service in correct order

you can try this:

    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);
    }
}

and use it like this:

 LinkedHashMap<String, ArrayList> fromJSON = fromJSON(
                json, LinkedHashMap.class);
Community
  • 1
  • 1
ShinChven
  • 473
  • 5
  • 11