Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building ordered JSON String from LinkedHashMap

I had a need for having Key/Value pairs in the order of my insertion, so I opted to use LinkedHashMap over HashMap. But I need to convert the LinkedHashMap into a JSON String where the order in the LinkedHashMap is maintained in the string.

But currently I'm achieving it by:

  1. First converting the LinkedHashMap into JSON.
  2. Then converting the JSON into a string.

    import java.util.LinkedHashMap;
    import java.util.Map;
    
    import org.json.JSONObject;
    
    public class cdf {
        public static void main(String[] args) {
            Map<String,String > myLinkedHashMap =  new LinkedHashMap<String, String>();
            myLinkedHashMap.put("1","first");
            myLinkedHashMap.put("2","second");
            myLinkedHashMap.put("3","third");
    
            JSONObject json = new JSONObject(myLinkedHashMap);
            System.out.println(json.toString());
        }
    }
    

The output is:

{"3":"third","2":"second","1":"first"} . 

But I want it in the order of insertion of the keys, like this:

{"1":"first","2":"second","3":"third"}

Once I convert the LinkedHashMap into a JSON it loses it order (it's obvious that JSON doesn't have the notion of order) and hence the string too is out of order. Now, how do I generate a JSON string whose order is same as the LinkedHashMap?

like image 952
Karthic Rao Avatar asked Apr 07 '15 12:04

Karthic Rao


People also ask

How do I make json ordered?

In this example you will know how to order json elements as you desire. By default the json elements will be placed in random order. By using @JsonPropertyOrder annotation, you can get the json in your desired order. The below class gives you an example on how to use @JsonPropertyOrder annotation.

How do I print from LinkedHashMap?

Algorithm: Use For-each loop to iterate through LinkedHashMap. Using entrySet() method which gives the set structure of all the mappings of the map for iterating through the whole map. For each iteration print its respective value.

How do I cast a LinkedHashMap to a list?

To convert all values of the LinkedHashMap to a List using the values() method. The values() method of the LinkedHashMap class returns a Collection view of all the values contained in the map object. You can then use this collection to convert it to a List object.

How do I print a LinkedHashMap key?

Method 1: Use for-each loop to iterate through LinkedHashMap. For each iteration, we print the respective key using getKey() method. for(Map. Entry<Integer,Integer>ite : LHM.


1 Answers

Gson if your friend. This will print the ordered map into an ordered JSON string.

If you want to preserve insertion order, use a LinkedHashMap.

I used the latest version of Gson (2.8.5), you can can download it via the following options at the bottom of this post.

import java.util.*;
import com.google.gson.Gson;

public class OrderedJson {
    public static void main(String[] args) {
        // Create a new ordered map.
        Map<String,String> myLinkedHashMap = new LinkedHashMap<String, String>();

        // Add items, in-order, to the map.
        myLinkedHashMap.put("1", "first");
        myLinkedHashMap.put("2", "second");
        myLinkedHashMap.put("3", "third");

        // Instantiate a new Gson instance.
        Gson gson = new Gson();

        // Convert the ordered map into an ordered string.
        String json = gson.toJson(myLinkedHashMap, LinkedHashMap.class);

        // Print ordered string.
        System.out.println(json); // {"1":"first","2":"second","3":"third"}
    }
}

If you want the items to always be inserted at the right place, use a TreeMap instead.

import java.util.*;
import com.google.gson.Gson;

public class OrderedJson {
    public static void main(String[] args) {
        // Create a new ordered map.
        Map<String,String> myTreeHashMap = new TreeMap<String, String>();

        // Add items, in any order, to the map.
        myTreeHashMap.put("3", "third");
        myTreeHashMap.put("1", "first");
        myTreeHashMap.put("2", "second");

        // Instantiate a new Gson instance.
        Gson gson = new Gson();

        // Convert the ordered map into an ordered string.
        String json = gson.toJson(myTreeHashMap, TreeMap.class);

        // Print ordered string.
        System.out.println(json); // {"1":"first","2":"second","3":"third"}
    }
}

Dependency Options

Maven

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>

Gradle

compile 'com.google.code.gson:gson:2.8.5'

Or you can visit Maven Central for more download options.

like image 136
Mr. Polywhirl Avatar answered Sep 19 '22 13:09

Mr. Polywhirl