JAVA生成json格式的數(shù)據(jù), 這里使用import org.json.JSONObject;
先加載所需要的jar包
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
JSONObject jsonObject = new JSONObject();
jsonObject.put("names","莊子");
jsonObject.put("sex", "男");
String[] hobby = {"游泳","打籃球"};
jsonObject.put("hobbies", Arrays.asList(hobby)); //添加數(shù)組
HashMap<String,Integer> map = new HashMap<String,Integer>();
map.put("eng",100);
map.put("math",99);
map.put("chinese",98);
jsonObject.put("score", map);
System.out.println(jsonObject);//添加HashMap對(duì)象
out.println(jsonObject);
顯示結(jié)果如下:
{"score":{"chinese":98,"math":99,"eng":100},"names":"莊子","hobbies":["游泳","打籃球"],"sex":"男"}
解析結(jié)果如下:
AJAX請(qǐng)求結(jié)果如下:
方法二:加載阿里的fastjson2包
HashMap<String, Object> hm = new HashMap<>();
hm.put("name","小強(qiáng)");
hm.put("sex","男");
String[] h = {"牛奶","香蕉"};
hm.put("h",h);
String json = JSON.toJSONString(hm);
response.getWriter().println(json);
