List集合轉換成Json字符串
第一種方法:
public static JSONArray getJson(List<People> list) {
JSONArray json = new JSONArray();
try {
for (People people : list) {
JSONObject jo = new JSONObject();
jo.put("id", people.getName());
jo.put("time", people.getAge());
json.put(jo);
}
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
第二種方法:
導入com.alibaba:fastjson:1.2.56庫
String json = JSON.toJSONString(list);
Map集合轉換成Json字符串
導入com.google.code.gson:gson:2.8.5庫
Gson gson=new Gson();
String json=gson.toJson(map);