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
-
1This link will help you: stackoverflow.com/questions/12155800/…Kartic– Kartic2016年03月02日 06:39:40 +00:00Commented 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 keycreative Pro– creative Pro2016年03月02日 06:51:09 +00:00Commented Mar 2, 2016 at 6:51
-
@creative Pro did you tried my solutionsanky jain– sanky jain2016年03月02日 07:07:48 +00:00Commented Mar 2, 2016 at 7:07
3 Answers 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
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
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
lang-java