I needed to have Key / Value pairs in the order of my insertion, so I decided to use LinkedHashMap over HashMap . But I need to convert LinkedHashMap to a JSON string, where the order in LinkedHashMap maintained in the string.
But currently I am achieving this:
- First conversion of LinkedHashMap to JSON.
Then convert JSON to 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()); } }
Output:
{"3":"third","2":"second","1":"first"} .
But I want it in the order of key insertion, for example:
{"1":"first","2":"second","3":"third"}
As soon as I convert LinkedHashMap to JSON, it loses its order (it is obvious that JSON has no concept of order), and therefore the line is also out of order. Now, how do I create a JSON string with the same order as LinkedHashMap ?
source share