I downloaded some information in json format, but it looks different from what I am regularly used to.
The basic structures consists of two objects: an array of arrays without keys and an array of objects with key:value pairs, indicating the "keys" for the first array and their type.
{
"datatable": {
"data": [
[
"2022-04-26",
118313,
0,
"QQQ",
null,
"BL6CD96",
"ARCAVA4600V8",
"XBUE",
"INVESCO QQQ TRUST SE1-CEDEAR",
"Invesco QQQ Trust Series 1",
"False",
"False"
],
[
"2022-04-26",
56360,
22669,
"QQQ",
"46090E103",
"BDQYP67",
"US46090E1038",
"XNAS",
"INVESCO QQQ TRUST SERIES 1",
"Invesco QQQ Trust Series 1",
"True",
"False"
],
[
"2022-04-26",
44307,
25533,
"IBM",
"459200101",
"2005973",
"US4592001014",
"XNYS",
"INTL BUSINESS MACHINES CORP",
"International Business Machines Corp",
"True",
"True"
]
],
"columns": [{
"name": "marketdate",
"type": "Date"
},
{
"name": "seckey",
"type": "Integer"
},
{
"name": "securityid",
"type": "Integer"
},
{
"name": "ticker",
"type": "text"
},
{
"name": "cusip",
"type": "text"
},
{
"name": "sedol",
"type": "text"
},
{
"name": "isin",
"type": "text"
},
{
"name": "mic",
"type": "text"
},
{
"name": "securityname",
"type": "text"
},
{
"name": "companyname",
"type": "text"
},
{
"name": "uslisted",
"type": "text"
},
{
"name": "innqgi",
"type": "text"
}
]
},
"meta": {
"next_cursor_id": null
}
}
Result I am trying to achieve:
{
"datatable": {
"data": [
[
"marketdate":"2022-04-26",
"seckey":118313,
"securityid":0,
"ticker":"QQQ",
"cusip":"null",
"sedol":"BL6CD96",
"isin":"ARCAVA4600V8",
"mic":"XBUE",
"securityname":"INVESCO QQQ TRUST SE1-CEDEAR",
"companyname":"Invesco QQQ Trust Series 1",
"uslisted":"False",
"innqgi":"False"
],
...
},
"meta": {
"next_cursor_id": null
}
}
How can I convert this into a regular key=value JSON OR
How do I parse this in Java so that I have a POJO where the variable names = "colName"?
Thanks a lot!
Nikhil
You need to map column names from second array to values from first array using indexes. First let's create POJO structure.
public class DataObject {
private LocalDate marketDate;
private int secKey;
private int securityId;
private String ticker;
private String cusip;
private String sedol;
private String isin;
private String mic;
private String securityName;
private String companyName;
private String uslisted;
private String innqgi;
//getters and setters
}
Then:
public class DataWrapper {
private List<DataObject> data;
//getters setters
}
Response:
public class Response {
private DataWrapper datatable;
//getters setters
//omitting meta
}
Then create deserializer to map column names to corresponding values:
public class ResponseDeserializer extends StdDeserializer<Response> {
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private final Map<String, BiConsumer<JsonNode, DataObject>> map = new HashMap<>();
public ResponseDeserializer() {
super(Response.class);
this.initMap();
}
private void initMap() {
map.put("marketdate", (jsonNode, dataObject) -> dataObject.setMarketDate(LocalDate.parse(jsonNode.asText(), FORMATTER)));
map.put("seckey", (jsonNode, dataObject) -> dataObject.setSecKey(jsonNode.asInt()));
map.put("cusip", (jsonNode, dataObject) -> dataObject.setCusip(jsonNode.asText()));
//do the same for rest
}
#Override
public Response deserialize(JsonParser parser, DeserializationContext context) throws IOException {
JsonNode root = parser.getCodec().readTree(parser);
ArrayNode dataArray = (ArrayNode) root.get("datatable").get("data");
ArrayNode columnsArray = (ArrayNode) root.get("datatable").get("columns");
List<DataObject> objects = new ArrayList<>(dataArray.size());
for (int index = 0; index < dataArray.size(); index++) {
ArrayNode data = (ArrayNode) dataArray.get(index);
DataObject dataObject = new DataObject();
for (int dadaIndex = 0; dadaIndex < data.size(); dadaIndex++) {
JsonNode node = data.get(dadaIndex);
String columnName = columnsArray.get(dadaIndex).get("name").asText();
this.map.getOrDefault(columnName, (jsonNode, dataObject1) -> {}).accept(node, dataObject);
}
objects.add(dataObject);
}
DataWrapper wrapper = new DataWrapper();
wrapper.setData(objects);
Response response = new Response();
response.setDatatable(wrapper);
return response;
}
}
Here i am using a Map to map column name to operation setting the value, but you could do it with reflection as well, for example.
A serializer to parse local date to the same format as in input:
public class LocalDateSerializer extends StdSerializer<LocalDate> {
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
public LocalDateSerializer() {
super(LocalDate.class);
}
#Override
public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider provider) throws IOException {
gen.writeString(FORMATTER.format(value));
}
}
Register serializers/deserializers and test result:
public class Main {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Response.class, new ResponseDeserializer());
module.addSerializer(LocalDate.class, new LocalDateSerializer());
mapper.registerModule(module);
Response response = mapper.readValue(inputJson, Response.class);
String json = mapper.writeValueAsString(response);
System.out.println(json);
}
}
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
class HashMapExample {
private static HashMap<String, Integer> bigHashMap;
public static void main(String[] args) {
try {
JSONObject jsonObject = getJsonFromSource();
// Get datatable object from JSONObject
JSONObject dataTable = (JSONObject) jsonObject.get("datatable");
if (dataTable != null) {
// Get JSONArray from JSONObject datatable
JSONArray data = dataTable.getJSONArray("data");
JSONArray columns = dataTable.getJSONArray("columns");
mapToKeyValuePair(data, columns); // Map key to value
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
private static void mapToKeyValuePair(final JSONArray dataArray, final JSONArray columnsArray) {
// Check for equal lengths
if ((dataArray != null) && (columnsArray != null)) {
ArrayList<String> fieldNames = new ArrayList<>(); // ArrayList with field names
ArrayList<String> dataValuesArrays = new ArrayList<>(); // ArrayList with the data values
ArrayList<HashMap> wholeFinalArray = new ArrayList<>(); // The whole array with key pair value
// Loop to get a JSONObject with all the column names
for (int i = 0; i < columnsArray.length(); i++) {
JSONObject jsonObjectColumn = (JSONObject) columnsArray.get(i); // Get JSONObject with column names
fieldNames.add(jsonObjectColumn.get("name").toString()); // Get fieldNames from JSONObject above
}
for (int i = 0; i < dataArray.length(); i++) {
JSONArray jsonArrayData = (JSONArray) dataArray.get(i); // Get JSONArray with data
dataValuesArrays.add(jsonArrayData.toString()); // Add the data to an ArrayList
}
// Loop through the data values combined arrays
for (String dataValuesArray : dataValuesArrays) {
JSONArray singleDataArray = new JSONArray(dataValuesArray); // Get single data array
for (int a = 0; a < singleDataArray.length(); a++) {
HashMap<String, String> item = new HashMap<>();
item.put(fieldNames.get(a), singleDataArray.get(a).toString());
wholeFinalArray.add(item);
}
}
System.out.println(wholeFinalArray);
}
}
private static JSONObject getJsonFromSource() {
String jsonResponse = "{'datatable':{'data': [['2022-04-26', 118313, 0, 'QQQ', null, " +
"'BL6CD96', " +
"'ARCAVA4600V8', 'XBUE', 'INVESCO QQQ TRUST SE1-CEDEAR', 'Invesco QQQ Trust Series 1', 'False', 'False'],['2022-04-26', 56360, 22669, 'QQQ', '46090E103', 'BDQYP67', 'US46090E1038', 'XNAS', 'INVESCO QQQ TRUST SERIES 1', 'Invesco QQQ Trust Series 1', 'True', 'False'],['2022-04-26', 44307, 25533, 'IBM', '459200101', '2005973', 'US4592001014', 'XNYS', 'INTL BUSINESS MACHINES CORP', 'International Business Machines Corp', 'True', 'True']],'columns': [{'name':'marketdate', 'type':'Date'},{'name':'seckey', 'type':'Integer'},{'name':'securityid', 'type':'Integer'},{'name':'ticker', 'type':'text'},{'name':'cusip', 'type':'text'},{'name':'sedol', 'type':'text'},{'name':'isin', 'type':'text'},{'name':'mic', 'type':'text'},{'name':'securityname', 'type':'text'},{'name':'companyname', 'type':'text'},{'name':'uslisted', 'type':'text'},{'name':'innqgi', 'type':'text'}]}, 'meta':{'next_cursor_id':null}}";
return new JSONObject(jsonResponse);
}
}
Related
Im trying to make a JAVA application that makes a json file with the data that i send, but when i send new data, the last data the data is just replaced
the first method called
az.addUser("John", "10", "star");
the JSON
{
"user" : {
"name": "john",
"score": "10",
"type": "star"
}
}
second method called
az.addUser("Kevin", "20", "energy");
The JSON Expected
{
"user" : {
"name": "john",
"score": "10",
"type": "star"
}
"user" : {
"name" = "Kevin",
"score" = "20",
"type" = "energy"
}
}
the REAL JSON
{
"user" : {
"name" = "Kevin",
"score" = "20",
"type" = "Energy"
}
}
The Method
public void addUser(String name, String score, String type){
FileWriter wf = new FileWriter("exit.json");
JSONObject json;
JSONObject jsonInternal = new JSONObject();
jsonInternal.put("name", name);
jsonInternal.put("score", score);
jsonInternal.put("type", type);
json = new JSONObject();
json.put("user", jsonInternal);
wf.write(json.toJSONString());
wf.close();
}
You need to write a JSON array, not a JSON object. The code below is strictly pseudocode, as I do not know which library JSONObject comes from.
import java.io.FileWriter;
import java.io.IOException;
public class UserListWriter {
private String filename;
private JSONArray usersJson;
public UserListWriter(String filename) {
this.filename = filename;
this.usersJson = new JSONArray();
}
public UserListWriter addUser(String name, int score, String type) {
JSONObject userJson = new JSONObject();
userJson.put("name", name);
userJson.put("score", score);
userJson.put("type", type);
usersJson.put(userJson);
return this;
}
public UserListWriter write() throws IOException {
FileWriter wf = new FileWriter(this.filename);
wf.write(usersJson.toJSONString());
wf.close();
return this;
}
public static void main(String[] args) {
try {
new UserListWriter("exit.json")
.addUser("John", 10, "star")
.addUser("Kevin", 20, "energy")
.write();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Theoretical output:
[{
"name": "John",
"score": 10,
"type": "star"
}, {
"name": "Kevin",
"score": 20,
"type": "energy"
}]
How I can get the "fields" objects 0,1,2,3,4 & only the "name" object string of every object using JSONOBJECT
[
{
"name": "Bank1",
"fields": {
"0": {
"name": "Email",
"slug": "email",
"type": "input"
},
"1": {
"name": "City",
"slug": "city",
"type": "input"
},
"2": {
"name": "Screenshot",
"slug": "screenshot",
"type": "file"
},
"3": {
"name": "Full Name",
"slug": "full-name",
"type": "input"
}
},
"status": "Active"
},
{
"name": "Bank2",
"fields": {
"0": {
"name": "Email",
"slug": "email",
"type": "input"
},
"1": {
"name": "City",
"slug": "city",
"type": "input"
},
"2": {
"name": "Screenshot",
"slug": "screenshot",
"type": "file"
},
"4": {
"name": "Submitted Date",
"slug": "submitted-date",
"type": "calendar"
}
},
"status": "Active"
}
]
& this is what I try to done
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String p_name = jsonObject.getString("name");
JSONObject jo = jsonObject.getJSONObject("fields");
String j1 = jo.getString("0");
if (!j1.isEmpty()){
JSONObject jo1 = jo.getJSONObject("0");
String f_name1 = jo1.getString("name");
Log.d("Field1.", f_name1);
}
}}catch block...
but the problem is, it gives me value of the object null like [value 4 is null] cuz there is no object for 4 in the first object of fields. please help me solve this prob, appreciate your answers thankyou :)
You can use keys() iterator of json object & loop on it using while (keys.hasNext())
For your example, it would look something like this:
private void parseJson(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject jo = jsonObject.getJSONObject("fields");
Iterator<String> keys = jo.keys();
while (keys.hasNext()) {
String key = keys.next();
JSONObject jo1 = jo.getJSONObject(key);
String f_name1 = jo1.getString("name");
Log.d("Field1.", f_name1);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
There are some problems with get all keys properly in my IDE/JDK11, so I decided to loop over an ArrayList, basing on #MayurGajra solution, ex:
private static List<List<String>> parseJson(String response) throws JSONException {
JSONArray jsonArray = new JSONArray(response);
List<List<String>> result = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject jo = jsonObject.getJSONObject("fields");
List<Object> list = new ArrayList<>();
jo.keys().forEachRemaining(list::add);
List<String> subList = new ArrayList<>();
for (Object o : list) {
String key;
if (isString(o))
key = (String) o;
else
continue;
JSONObject jo1 = jo.getJSONObject(key);
String f_name1 = jo1.getString("name");
subList.add(f_name1);
}
result.add(subList);
}
return result;
}
private static boolean isString(Object o) {
try {
String result = (String) o;
} catch (ClassCastException e) {
return false;
}
return true;
}
The result obtained after processing the above json is as follows:
[[Email, City, Screenshot, Full Name], [Email, City, Screenshot, Submitted Date]]
but it have not to be a List of Lists ;)
-- edit --
To get only first list of elements labeled "name":
try {
System.out.println(parseJson(yourJsonAsString).get(0).toString());
} catch (JSONException e) {
System.out.println("JSONException:" + e.getMessage());
}
The result of above is:
[Email, City, Screenshot, Full Name]
I am new to use gson.
I found a lots of tutorial there I can learn of gson but there are using recylerview and model file.
JsonObjectRequest request = new JsonObjectRequest(LoginUrl, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG , String.valueOf(response));
try {
String statusObject = response.getString("status");
String msgObject = response.getString("msg");
if (statusObject.equals("200")) {
JSONArray jsonArray = response.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject managerResponse= jsonArray.getJSONObject(i);
// userIdObject = managerResponse.getString("user_id");
// String nameObject = managerResponse.getString("name");
// String emailObject = managerResponse.getString("email");
// String mobileObject = managerResponse.getString("mobile");
// String postobject = managerResponse.getString("post");
// pojectObject = managerResponse.getString("project");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
}
Here I can get data from jsonrequest using volley but unable to do that same process using volley and gson. Is there any way to use gson?
Thank You.
Update
My JSON Response
{
"status": "200",
"msg": "Successfully",
"response": [
{
"user_id": "1",
"name": "HEMANT OJHA",
"email": "hemguna#gmail.com",
"mobile": "9584919991",
"address1": "C92, PALLAWI NAGAR BABADIYA KALAN",
"user": "admin",
"api_token": "admin"
}
]
}
Generating POJO class from JSON
// Considering your response consists of json objects & json array
// Create a POJO class for your response with the link above
{
"keyOne": 1,
"keyTwo": "Some Value",
"someArray": [{
"key": "Value"
},
{
"key": "Value"
}
]
}
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ExampleClass {
#SerializedName("keyOne")
#Expose
private int keyOne;
#SerializedName("keyTwo")
#Expose
private String keyTwo;
#SerializedName("someArray")
#Expose
private List<SomeArray> someArray = null;
public int getKeyOne() {
return keyOne;
}
public void setKeyOne(int keyOne) {
this.keyOne = keyOne;
}
public String getKeyTwo() {
return keyTwo;
}
public void setKeyTwo(String keyTwo) {
this.keyTwo = keyTwo;
}
public List<SomeArray> getSomeArray() {
return someArray;
}
public void setSomeArray(List<SomeArray> someArray) {
this.someArray = someArray;
}
}
// Parsing JSON response with GSON
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
ExampleClass resultObj = gson.fromJson(jsonObject.toString(), ExampleClass.class);
int keyOneValue = resultObj.getKeyOne() // First JSON Object
// Getting String value
String keyTwoValue = resultObj.getKeyTwo() // Second JSON Object
List<SomeArray> yourJSONArray = resultObj.getSomeArray() // Getting JSON Array contents
// Depending on JSON response that you've updated in your question
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
ExampleClass resultObj = gson.fromJson(jsonObject.toString(),ExampleClass.class);
String status = resultObj.getStatus();
String msg = resultObj.getMsg();
List<Response> responseList = resultObj.getResponse();
The best way to use for entire app is create a Utils class and use it for conversion.
GsonUtils.java
// This Class is useful for mapping Json into Java Objects and vice versa.
public class GsonUtils {
private static final Gson gson = new Gson();
// This will Convert Java Objects into JSON String...
public static String toGson(Object object) {
return gson.toJson(object);
}
// Gives Java Objects from JSON
public static <T> T fromGson(String json, Class<T> type) {
return gson.fromJson(json, type);
}
public static JsonArray fromGson(String json) {
return new JsonParser().parse(json).getAsJsonArray();
}
}
Now convert any json to and from POJO via,
POJO pojoObj = GsonUtils.toGson(POJO.class);
Try this
JSON response
String str = new Gson().toJson(response)
I like to know how I might do the following:
I want to create a json format of the following:
I want to be able to create a recursive function that takes an object holding a list of other objects of the same type and in a method to recursively create the format below.
{
"name": "lib",
"contains": [{
"name": "room",
"contains": [{
"name": "bookshelf",
"contains": [{
"name": "shelf",
"contains": []
}]
}]
}]
}
I have this as the following method:
private JSONObject json = new JSONObject();
public JSONObject setupLib(Contains contain) {
int count = contain.getContainerList().size();
for(int i = 0; i < count; i++){
try {
json.put("name", contain.getContainerList().get(i).getContainerName());
if(contain.getContainerList().size() != 0) {
Contains contains = (Contains) contain.getContainerList().get(i);
JSONArray array = new JSONArray();
json.put("contain",array.put(setupLib(contains)));}
}catch (JSONException e){
Log.i(Tag, e.getMessage());
}
}
return json;
}
I get a stackoverflow on the array/object
Two options
Do it yourself recursively
Use a library such as Gson to save you the development time and effort
Since this is a learning experience, I have shown both that return this JSON.
{
"name": "lib",
"contains": [{
"name": "room",
"contains": [{
"name": "bookshelf",
"contains": [{
"name": "shelf",
"contains": []
}]
}]
}]
}
public static void main(String[] args) {
Contains lib = new Contains("lib");
Contains room = new Contains("room");
Contains bookshelf = new Contains("bookshelf");
Contains shelf = new Contains("shelf");
bookshelf.add(shelf);
room.add(bookshelf);
lib.add(room);
// Option 1
System.out.println(setupLib(lib).toJSONString());
// Option 2
Gson gson = new Gson();
System.out.println(gson.toJson(lib));
}
private static JSONObject setupLib(Contains contain) {
if (contain == null) return null;
LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
JSONArray array = new JSONArray();
for (Contains c : contain.getContainerList()) {
JSONObject innerContain = setupLib(c);
if (innerContain != null) {
array.add(innerContain);
}
}
map.put("name", contain.getName());
map.put("contains", array);
return new JSONObject(map);
}
This is the model object, for reference
public class Contains {
#SerializedName("name")
#Expose
private String name;
#SerializedName("contains")
#Expose
private List<Contains> contains;
public Contains(String name) {
this.name = name;
contains = new ArrayList<Contains>();
}
public void setName(String name) {
this.name = name;
}
public void add(Contains c) {
this.contains.add(c);
}
public void setContainerList(List<Contains> contains) {
this.contains = contains;
}
public String getName() {
return name;
}
public List<Contains> getContainerList() {
return this.contains;
}
}
I think is far easier if you'd serialize both the JSONObject and Contains classes. This way you'll be able to use the Jackson library to create the JSON file for you.
You can find more information about the Jackson library on the following GitHub page: https://github.com/FasterXML/jackson.
With the values present inside the Map DataStructure i am creating a JSON dynamically .
The JSON its getting created is
{
"item": {
"T1": [
{
"name": "Ice creams",
"T2": [
{
"name": "Ice creams***Stick",
"T3": [
{
"T4": [
{
"name": "Ice creams***Stick***KoolCool***Strawbeerry",
"leaf": [
{
"crust_name": "crust"
}
]
}
],
"name": "Ice creams***Stick***KoolCool"
}
]
}
]
}
]
}
}
The problem is that the name under T3 is being appended at some other place rather than after it ,which should actually be
{
"item": {
"T1": [
{
"name": "Ice creams",
"T2": [
{
"name": "Ice creams***Stick",
"T3": [
{
"name": "Ice creams***Stick***KoolCool",
"T4": [
{
"name": "Ice creams***Stick***KoolCool***Strawbeerry",
"leaf": [
{
"crust_name": "crust"
}
]
}
]
}
]
}
]
}
]
}
}
Functionally there should be no difference between name being first or second in the property list,but this JSON would be passed to the Front End and the search functionality is breaking down ,if it not follows the structure
could anybody please let me know how to make the name appear after T3 ??
Please see this fiddle
http://jsfiddle.net/5wvqkb82/
This is my Java Program.
package com.services;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Test {
private static JSONObject processString(String data, int level,String key) throws JSONException {
JSONObject json = new JSONObject();
JSONArray leafjsonarray = new JSONArray();
int index = data.indexOf(',');
String name = data;
String remainder = "";
if (index < 0) {
index = name.indexOf('(');
if (index > 0) {
name = data.substring(0, index);
}
} else {
name = data.substring(0, index);
remainder = data.substring(name.length() + 1);
}
String fullpath = key+"***"+name;
json.put("name", fullpath);
JSONArray a = new JSONArray();
if (remainder.length() > 0) {
a.put(processString(remainder, level + 1,fullpath));
json.put("T" + level, a);
}
else {
JSONObject leafjsonObj = new JSONObject();
leafjsonObj.put("crust_name", "crust");
leafjsonarray.put(leafjsonObj);
json.put("leaf", leafjsonarray);
}
return json;
}
private static JSONArray processList(List<String> list, int level,String key) throws JSONException {
JSONArray json = new JSONArray();
for (String data : list) {
json.put(processString(data, level,key));
}
return json;
}
private static JSONArray processMap(Map<String, List<String>> map, int level) throws JSONException {
JSONArray array =new JSONArray();
for (String key : map.keySet()) {
JSONObject json = new JSONObject();
json.put("name", key);
json.put("T" + level, processList(map.get(key), level + 1,key));
array.put(json);
}
return array;
}
public static void main(String args[]) {
Map<String, List<String>> consilatedMapMap = new LinkedHashMap<String, List<String>>();
List<String> values = new LinkedList<String>();
values.add("Stick,KoolCool,Strawbeerry(25)");
// values.add("Cone,SSS(25)");
/* List<String> values2 = new LinkedList<String>();
values2.add("Bucket(25)");
*/
//consilatedMapMap.put("Popcorn", values2);
consilatedMapMap.put("Ice creams", values);
try {
int level = 2;
JSONArray json = processMap(consilatedMapMap, level);
JSONObject jsonT1 = new JSONObject();
jsonT1.put("T1",json);
JSONObject sai = new JSONObject();
sai.put("item",jsonT1);
System.out.println(sai);
} catch(JSONException x) {
x.printStackTrace();
System.exit(-1);
}
}
}
You need to take a look at this. Basically, you cannot rely on the order of the objects. If you need them to be in an order, you should use JSON Arrays.
If you want to use Arrays, your whole ordering will be messed up, for example:
"T4": [
{
"name": "Ice creams***Stick***KoolCool***Strawbeerry",
"leaf": [
{
"crust_name": "crust"
}
]
}
]
will become
"T4": [
{
"name": "Ice creams***Stick***KoolCool***Strawbeerry"
},
{
"leaf": [
{
"crust_name": "crust"
}
]
}
]
You have used JSON Arrays in your program, make use of it and figure it out if you really want to go ahead with this way.