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:
- First converting the LinkedHashMap into JSON.
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
?