Search code examples
javajsonstring-building

How to "split" Map values among different JSON arrays?


I have a multiMap with following values:

a=1,b=2,c=3

I want to create a JSON out of it in following format:

[{"data":["a","b","c"],"StaticData":"HELLO"},{"Categories":[1,2,3]}]

I am trying to use String buffer but am completely lost how to put the loop for only keys and only values and how to insert some static data in between.

I thought if i could first create a string and later parse in the json format or is there any other way to form a json?


Solution

  • First iterate your HashMap to get keys and values and store it in List. Create two class one contain List of keys and staticData and other will contain List of Category. Set values in class object, Create one List and add this two object of class into list and serialize this list into JSON.

    I have use Gson Library for the onvert object into JSON string.

    Here is code for what you want.

    DataClass :

    public class DataClass {
        private List<String> data;
        private String StaticData;  
        //your getter and setter method.
    }  
    

    CategoryClass :

    public class CategoryClass {
       private List<String> Categories;  
       //your getter and setter method
    }  
    

    TestClass :

    public static void main(String[] args) {
        try{
            Map<String, String> map = new HashMap<String, String>();
            map.put("a", "1");
            map.put("b", "2");
            map.put("c", "3");
    
            List<Object> obj = new ArrayList<Object>();  
    
    
            List<String> keys = new ArrayList<String>();
            List<String> values = new ArrayList<String>();
    
            for(Entry<String, String> myMap : map.entrySet()){
                keys.add(myMap.getKey());
                values.add(myMap.getValue());
            }  
    
            DataClass dataObj = new DataClass();
            dataObj.setData(keys);
            dataObj.setStaticData("HELLO");
            obj.add(dataObj);
    
            CategoryClass catObj  = new CategoryClass();
            catObj.setCategories(values);
            obj.add(catObj);
    
            Gson gson = new Gson();  
            String jsonStr = gson.toJson(obj);
            System.out.println(jsonStr);
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
    }
    

    OutPut :

    [{"data":["b","c","a"],"StaticData":"HELLO"},{"Categories":["2","3","1"]}]    
    

    EDIT :

    If your need to maintain order of insert in Map than use LinkedHashMap so that ordre of keys and values are same as insert in Map.