JSON Java Data Process different format
Many times when we worked on processing data in JSON format using Java its confusing to convert object in different format. Below example you will see how to create JSON data in different format:
Note: To execute below examples you will have include json.jar in your classpath. You could also download full source code in the bottom.
Example 1: If you want to process data in below format:
[ { "values": [ [ 1025409600000, 23 ], [ 1028088000000, 19 ], [ 1030766400000, 21 ], [ 1033358400000, 22 ] ], "key": "North America" }, { "values": [ [ 1025409600000, 23 ], [ 1028088000000, 19 ], [ 1030766400000, 21 ], [ 1033358400000, 22 ] ], "key": "North America" }, { "values": [ [ 1025409600000, 23 ], [ 1028088000000, 19 ], [ 1030766400000, 21 ], [ 1033358400000, 22 ] ], "key": "North America" }, { "values": [ [ 1025409600000, 23 ], [ 1028088000000, 19 ], [ 1030766400000, 21 ], [ 1033358400000, 22 ] ], "key": "North America" } ]
Java Program:
package com.javahonk.controller; import org.json.JSONArray; import org.json.JSONObject; public class CreateJACKSONJSONObject { public static void main(String[] args) { JSONObject jo = new JSONObject(); jo.put("values", new JSONArray(new Long[][]{{1025409600000L,23L},{1028088000000L,19L},{1030766400000L,21L},{1033358400000L,22L}})); jo.put("key", "North America"); JSONArray ja = new JSONArray(); ja.put(jo); ja.put(jo); ja.put(jo); ja.put(jo); System.out.println(ja); } }
Example 2: Create JSON data in below format:
[ { "values": "RIC 1", "key": "North America" }, { "values": "RIC 1", "key": "North America" } ]
Java Program:
package com.javahonk.controller; import org.json.JSONArray; import org.json.JSONObject; public class Test { public static void main(String[] args) { JSONObject jo = new JSONObject(); jo.put("values", "RIC 1"); jo.put("key", "North America"); JSONArray ja = new JSONArray(); ja.put(jo); ja.put(jo); System.out.println(ja); } }
Example 3: Create JSON data in below format:
[ { "values": [ [ 1136005200000, 1271000 ], [ 1138683600000, 1271000 ], [ 1141102800000, 1271000 ], [ 1143781200000, 0 ] ], "bar": true, "key": "Quantity" } ]
Java Program:
package com.javahonk.controller; import org.json.JSONArray; import org.json.JSONObject; public class CreateJSONObject { public static void main(String[] args) { JSONObject jo = new JSONObject(); jo.put("values", new JSONArray(new Long[][]{{1136005200000L,1271000L},{1138683600000L,1271000L},{1141102800000L,1271000L},{1143781200000L,0L}})); jo.put("key", "Quantity"); jo.put("bar", true); JSONArray ja = new JSONArray(); ja.put(jo); System.out.println(ja); } }
For more information please read this tutorial from Oracle
Download Project: StackedChartSpring