0

For example i have json:

{
   "1" : {...}, 
   "5" : {...}, 
   "2" : {...}
}

I want to parse it to List with same element positions:

So element with id = "1" will be in List on 0 position, with id="5" on 1 position, and with id="2" on 2 position.

If i do something like this:

HashMap<String, Object> res  = gson.fromJson(data.toString(), new TypeToken<HashMap<String, <MyClass>>() {}.getType());

and after that using iterator, get elements and add to List:

Set<Map.Entry<String, Object>> set = res.entrySet();
Iterator<Map.Entry<String, Object>> iterator = set.iterator();
while (iterator.hasNext()) {
      mMyList.add(0, (MyClass)entry.getValue());
}

I will have positions of elements not like in inpute json.

If i tried parse like this:

HashMap<String, JsonObject> threadsJSON = new HashMap<String, JsonObject>();
resJSON = gson.fromJson(data.toString(), new TypeToken<HashMap<String, JsonObject>>() {}.getType());
List<MyClass> msgs = new ArrayList<MyClass>();


Iterator itr = res.keySet().iterator();
while (itr.hasNext()) {
   String keyId = itr.next().toString();
    msgs.add(gson.fromJson(resJSON.get(keyId), MyClass.class));
 }

I will take List with positions not like in input json.

So, how should i parse json to make same positions of elements in output List?

Jaky71
  • 162
  • 1
  • 9

1 Answers1

3

HashMap does not guarantee iteration order. Try using a LinkedHashMap (which guarantees this property).

Florian Barth
  • 1,392
  • 12
  • 25