Search code examples
javajsonjsonreader

Reading a JSON file in order


I have this json file that have a map of key-value pairs, but each value is a list of values

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

I need to read them in a java class and convert this into an ordered hash. I know sets and hashes meant to be unordered, so if there is a way to get an ordered list of the keys only that would be very helpful. Also, if there is a way to reorder the info and get a list of keys that would be good too.


Solution

  • I think what you meant was a Map, not a Set. A set does not have a key whereas a Map does.

    • 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.

    So in your case, if you want to preserve the insertion order, you should use LinkedHashMap. If you want to order it by the key, you should use TreeMap.

    source

    Update

    To read it, you can use 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));