JAVA生成json格式的数据, 这里使用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)); //添加数组 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对象 out.println(jsonObject);
显示结果如下:
{"score":{"chinese":98,"math":99,"eng":100},"names":"庄子","hobbies":["游泳","打篮球"],"sex":"男"}
解析结果如下:
AJAX请求结果如下:
方法二:加载阿里的fastjson2包
HashMap<String, Object> hm = new HashMap<>(); hm.put("name","小强"); hm.put("sex","男"); String[] h = {"牛奶","香蕉"}; hm.put("h",h); String json = JSON.toJSONString(hm); response.getWriter().println(json);