0

I have a Map with a key and value as linked List as shown below

{Ice creams=[Cone,KoolCool(21), Stick,KoolCool(25)]}

With this i need to construct a following json

{
    "name": "Ice creams",
    "T2": [
        {
            "name": "Cone",
            "T3": [
                {
                    "name": "KoolCool",
                    "leaf": []
                }
            ]
        },
        {
            "name": "Stick",
            "T3": [
                {
                    "name": "KoolCool",
                    "leaf": []
                }
            ]
        }
    ]
}

Every comma seperated value will increment the T value

I am trying to apprach this with the below

  1. For every key in the Map Access its value as LinkedList
  2. From that LinkedList access split it and construct the json

Could anybody please let me know if there is a better way of doing this ??

package com.util;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
public class Test {
    public static void main(String args[]) {
        Map<String, LinkedList<String>> consilatedMapMap = new LinkedHashMap<String, LinkedList<String>>();
        LinkedList<String> values = new LinkedList<String>();
        values.add("Cone,KoolCool(21)");
        values.add("Stick,KoolCool(25)");
        consilatedMapMap.put("Ice creams", values);

        /*
         * for (Map.Entry<String, LinkedList<String>> consilMap :
         * consilatedMapMap.entrySet()) {
         * 
         * String t1Category = consilMap.getKey(); LinkedList<String>
         * consiladatedList = consilMap.getValue();
         * 
         * 
         * for(int i=0;i<consiladatedList.size();i++) { String result =
         * consiladatedList.get(i);
         * 
         * String spliter[] = result.split(",");
         * 
         * for(int j=0;j<spliter.length;j++) { System.out.println(spliter[j]); }
         * 
         * }
         * 
         * }
         */


    }

}
Pawan
  • 31,545
  • 102
  • 256
  • 434

3 Answers3

1

I believe you're overcomplicating this - autoincremented names... The JSON structure doesn't match the Java structure... JSON generated partly by object structure, partly by parsing strings within it... even though you say "Every comma seperated value will increment the T value" this is obviously not true from the example.

Nevertheless... this is possible - even just using org.json (not sure why people keep suggesting GSON as a fix all to this...)

The primary idea here is to make a method for each part you need to generate, and pass the "level" around to generate the appropriate "Tn" property when you need it.

public class Test {

    private static JSONObject processString(String data, int level) throws JSONException {
        JSONObject json = new JSONObject();
        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);
        }
        json.put("name", name);

        JSONArray a = new JSONArray();
        if (remainder.length() > 0) {
            a.put(processString(remainder, level + 1));
            json.put("T" + level, a);
        } else {
            json.put("leaf", a);
        }
        return json;
    }  

    private static JSONArray processList(List<String> list, int level) throws JSONException {
        JSONArray json = new JSONArray();
        for (String data : list) {
            json.put(processString(data, level));
        }
        return json;
    }  

    private static JSONObject processMap(Map<String>, List<String>> map, int level) throws JSONException {
        JSONObject json = new JSONObject();
        for (String key : map.keySet()) {
            json.put("name", key);
            json.put("T" + level, processList(map.get(key), level + 1));
        }
        return json;
    }        

    public static void main(String args[]) {
        Map<String, List<String>> consilatedMapMap = new LinkedHashMap<String, List<String>>();
        List<String> values = new LinkedList<String>();
        values.add("Cone,KoolCool(21)");
        values.add("Stick,KoolCool(25)");
        consilatedMapMap.put("Ice creams", values);

        try {
            int level = 2;
            JSONObject json = processMap(consilatedMapMap, level);
        } catch(JSONException x) {
            x.printStackTrace();
            System.exit(-1);
        }
}
Nate
  • 16,748
  • 5
  • 45
  • 59
  • Thank you very much , in case i add values.add("Stick,KoolCool,Sai(25)"); , why it isn't displaying T4 ?? – Pawan Aug 20 '14 at 14:12
  • So that's what "Every comma seperated value will increment the T value" meant... edited to add a recursive processString to handle this... – Nate Aug 20 '14 at 16:57
  • Could you please let me know how to make the name appear after T3(As its coming out of it currently)and this is breaking JS search http://jsfiddle.net/5wvqkb82/ – Pawan Aug 21 '14 at 04:48
  • Neither JSON or JavaScript guarantee an enumeration order of properties. Even if you generate the JSON by hand in a given order, there is no guarantee the properties will be accessed in that order once it's turned into a JavaScript object and you iterate over it's properties. – Nate Aug 21 '14 at 13:08
  • In the linked jsfiddle code at the end of your `recursiveSearch` function, inside the `if (isObject(json))` part. What you are doing now is iterating over all the properties and setting `startSaving = true` once you find the `name` property. Instead you should check for the `name` property on that object and that it equals the search term before you start the loop. I'm not completely sure what you wanted to return from the search in your example... I assumed it was all names of child nodes of the matched node? updated jsfiddle - http://jsfiddle.net/5wvqkb82/7/ – Nate Aug 21 '14 at 13:22
  • Could you please help me with http://stackoverflow.com/questions/25440431/how-to-make-it-add-it-to-the-existing-array – Pawan Aug 22 '14 at 06:26
0

There is a utility library called Gson on Google code.You can check it out here

For some simple examples visit this

0

Look at folowing code:

     Map<String, LinkedList<String>> consilatedMapMap = new LinkedHashMap<String, LinkedList<String>>();
     LinkedList<String> values = new LinkedList<String>();
     values.add("Cone,KoolCool(21)");
     values.add("Stick,KoolCool(25)");
     consilatedMapMap.put("Ice creams", values);

     Gson gson=new Gson();
     String jsonElement=gson.toJson(consilatedMapMap);
    System.out.println(jsonElement);

Output

{"Ice creams":["Cone,KoolCool(21)","Stick,KoolCool(25)"]}

As you can see from the code and it's output, Gson library would convert your data structure to a json string.

All you need is this Gson library.

Darshan Lila
  • 5,772
  • 2
  • 24
  • 34
  • But i need to add T2 , T3--- etc as required . – Pawan Aug 20 '14 at 12:45
  • Same works for T2, T3 etc. The json string will be generated accordingly. – Darshan Lila Aug 20 '14 at 12:46
  • Could you please show how to generate T2 , T3 in this case ?? – Pawan Aug 20 '14 at 12:49
  • Create a class T2 add fields you require in them use setters to set the values for the fields and put them into map. If you want a particular hierarchy of Json, I suggest you build a top level class with fields and put them into array list and later generate Json out of them. – Darshan Lila Aug 20 '14 at 12:57