user2696466 user2696466 - 4 months ago 15
Java Question

how to achieve string conversion of list of maps in java

How can i convert JSON string to format given below and back to JSON string.

List<Map<String, String>> variables =new ArrayList<>();


I tried searching for this. Only thing which i could find is converting list to array and then to string. But using

TypeA[] array = a.toArray(new TypeA[a.size()]);


does not seems feasible here.

Answer

Converting List<Map<String,String>> to JSON string :

public String listmap_to_json_string(List<Map<String, String>> list)
{       
    JSONArray json_arr=new JSONArray();
    for (Map<String, String> map : list) {
        JSONObject json_obj=new JSONObject();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            try {
                json_obj.put(key,value);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }                           
        }
        json_arr.put(json_obj);
    }
    return json_arr.toString();
}

Or simply using google gson library:

public String listmap_to_json_string(List<Map<String, String>> list){
    // Use toJson method to serialize list to Json
    return  new GsonBuilder().setPrettyPrinting().create().toJson(list);
}

Converting JSON string to List<Map<String,String>>:

public List<Map<String, String>> json_string_to_listmap(String json){   
    Gson gson = new Gson();
    Type type = new TypeToken<ArrayList<Map<String, String>>>() {}.getType();
    // Use fromJson method to deserialize json into an ArrayList of Map
    return gson.fromJson(json , type);
}

For more informations check this link.