How to preserve order of insertion in JSON ?
I use org.json API to create JSON Objects.
The Following Code is an example, regarding how to create JSON Object
import org.json.JSONObject;
JSONObject obj = new JSONObject();
obj.put("CPUNO",cpuNo);
obj.put("CPUUSED",value);
To Convert JSON to String,
String JSONString=obj.toString();
For Example, the order of insertion of following metrics is shown below.
(1) CPU ID,
(2) Time,
(3) CPU Value
Now while loading this JSON to data table, there is more chance for the order to be changed at creation of JSON Object itself. See the example below.
CPU Value,
Time,
CPU ID.
To address this issue, we shall use LinkedHashMap to store the elements and at last create as JSON, by this way the order of insertion is preserved.
import java.util.LinkedHashMap;
LinkedHashMap<String,Object> lhm=new LinkedHashMap<String, Object>();
lhm.put("CPUID", 1);
lhm.put("Time",time );
lhm.put("CPUVALUE;", 100) ;
//Convert LinkedHashMap to JSONObject
JSONObject json=new JSONObject( lhm );
I use org.json API to create JSON Objects.
The Following Code is an example, regarding how to create JSON Object
import org.json.JSONObject;
JSONObject obj = new JSONObject();
obj.put("CPUNO",cpuNo);
obj.put("CPUUSED",value);
To Convert JSON to String,
String JSONString=obj.toString();
- The issue which I am going to focus in this post is that, JSON Object does preserve the order of insertion.
- Normally We prefer JSON either, to load it to JQuery Datatable ( Since it supports Pagination ). So In this case Order is very important.
For Example, the order of insertion of following metrics is shown below.
(1) CPU ID,
(2) Time,
(3) CPU Value
Now while loading this JSON to data table, there is more chance for the order to be changed at creation of JSON Object itself. See the example below.
CPU Value,
Time,
CPU ID.
To address this issue, we shall use LinkedHashMap to store the elements and at last create as JSON, by this way the order of insertion is preserved.
import java.util.LinkedHashMap;
LinkedHashMap<String,Object> lhm=new LinkedHashMap<String, Object>();
lhm.put("CPUID", 1);
lhm.put("Time",time );
lhm.put("CPUVALUE;", 100) ;
//Convert LinkedHashMap to JSONObject
JSONObject json=new JSONObject( lhm );
No comments:
Post a Comment