按顺序读取 JSON 个文件

Reading a JSON file in order

我有这个 json 文件,它有一个键值对映射,但每个值都是一个值列表

{
     "car":["BMW", "AUDI"],
      "OS":["Mac", "Win", "Ubuntu"],
      "food":["Burger", "Taco"]
}

我需要在 java class 中读取它们并将其转换为有序哈希。我知道集合和散列是无序的,所以如果有一种方法可以获得有序的键列表,那将非常有帮助。 另外,如果有一种方法可以重新排序信息并获得一个键列表,那也很好。

我想你的意思是地图,而不是集合。集合没有键,而映射有。

  • HashMap is implemented as a hash table, and there is no ordering on keys or values.
  • TreeMap is implemented based on red-black tree structure, and it is ordered by the key.
  • LinkedHashMap preserves the insertion order
  • Hashtable is synchronized, in contrast to HashMap.

所以在你的情况下,如果你想保留插入顺序,你应该使用LinkedHashMap。如果你想按键排序,你应该使用TreeMap.

source

更新

要阅读它,您可以使用 Gson:

String json = "{'car':['BMW', 'AUDI'],'OS':['Mac', 'Win', 'Ubuntu'],'food':['Burger', 'Taco']}";

// Convert the JSON String in a LinkedHashMap (to keep the insertion order)
Map<String, List<String>> map = new Gson().fromJson(json, new TypeToken<LinkedHashMap<String, List<String>>>(){}.getType());

// Print it, for proof
map.forEach((k, v) -> System.out.println("k = " + k + " | v = " + v));