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
18.7k6 gold badges59 silver badges84 bronze badges
asked Mar 2, 2016 at 6:36
3
  • 1
    This link will help you: stackoverflow.com/questions/12155800/… Commented Mar 2, 2016 at 6:39
  • 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<HashMap<String,String>> with all data. I just want to prepare a JSON string from that as above. Also note that there is no JSON key Commented Mar 2, 2016 at 6:51
  • @creative Pro did you tried my solution Commented Mar 2, 2016 at 7:07

3 Answers 3

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();
}
answered Mar 2, 2016 at 6:55
Sign up to request clarification or add additional context in comments.

Comments

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"}]
answered Mar 2, 2016 at 7:01

Comments

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);
answered Mar 2, 2016 at 6:41

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.