GSON将HashMap解析为具有相同位置的List

时间:2015-02-13 11:22:14

标签: android gson android-json

例如我有json:

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

我想用相同的元素位置将其解析为List:

因此,id为“1”的元素将位于列表0位置,1位置为id =“5”,2位置为id =“2”。

如果我做这样的事情:

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

然后使用迭代器,获取元素并添加到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());
}

我将拥有与inpute json不同的元素位置。

如果我尝试这样解析:

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

我将把List的位置与输入json中的位置不同。

那么,我应该如何解析json以在输出List中创建相同的元素位置?

1 个答案:

答案 0 :(得分:3)

HashMap不保证迭代顺序。尝试使用LinkedHashMap(保证此属性)。