2

I want to create a String as follows.

[{ "Name":"David",
    "Age":"30"
  },
  {"Name":"Max",
   "Age":"20"
  }
]

How can we create this string using ArrayList<HashMap<String,String>> and JSON in Java?

Nayuki
  • 17,911
  • 6
  • 53
  • 80
creative Pro
  • 57
  • 1
  • 7
  • 1
    This link will help you: http://stackoverflow.com/questions/12155800/how-to-convert-hashmap-to-json-object-in-java – Kartic Mar 02 '16 at 06:39
  • http://www.json.org/javadoc/org/json/JSONObject.html is not working. Could you please explain a little bit? I am new to java. I have ArrayList> with all data. I just want to prepare a JSON string from that as above. Also note that there is no JSON key – creative Pro Mar 02 '16 at 06:51
  • @creative Pro did you tried my solution – sanky jain Mar 02 '16 at 07:07

3 Answers3

3

Try as below

public String listmap_to_json_string(List<HashMap<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();
}
sanky jain
  • 873
  • 1
  • 6
  • 14
2

My JSON library fits your use case exactly. For example:

ArrayList<HashMap<String,String>> outer = new ArrayList<HashMap<String,String>>();

HashMap<String,String> inner = new HashMap<String,String>();
inner.put("Name", "David");
inner.put("Age", "30");
outer.add(inner);

inner = new HashMap<String,String>();
inner.put("Name", "Max");
inner.put("Age", "20");
outer.add(inner);

//----------

import io.nayuki.json.Json;
String jsonText = Json.serialize(outer);
System.out.println(jsonText);

Output text:

[{"Age": "30", "Name": "David"}, {"Age": "20", "Name": "Max"}]
Nayuki
  • 17,911
  • 6
  • 53
  • 80
1

Try Jackson Mapper You can read some tutorials about it. You can write code, using Jackson in this manner:

ObjectMapper mapper = new ObjectMapper();
jsonString = mapper.writeValueAsString(listOfMap);
Javasick
  • 2,753
  • 1
  • 23
  • 35