Java开发难免要使用JSON传递数据,下面是我总结的几种回调方式。
推荐文章:JSON、JSONObject、JSONArray、Map之间的关系
方式一、返回Map集合
//返回Map集合
@RequestMapping("/findStudent")
@ResponseBody
public Map<String, Object> findStudent(MultipartFile file) {
Student student = new Student();
student.setUsername("木心");
student.setPassword("123456");
Map map = new HashMap<String, Object>();
map.put("code", 1);
map.put("msg", "成功");
map.put("student",student);
return map;
}
方式二、返回JSON对象
//返回JSONObject对象
@RequestMapping(value = "/findStudent2")
@ResponseBody
public JSONObject findStudent2(String id){
Student student = new Student();
student.setUsername("木心");
student.setPassword("123456");
JSONObject jsonObject = new JSONObject();
jsonObject.put("code", 1);
jsonObject.put("msg", "成功");
jsonObject.put("student",student);
return jsonObject;
}
方式三、返回JSON数组
//返回JSON数组
@RequestMapping(value = "/findStudent3")
@ResponseBody
public JSONArray findStudent3(String id){
Student student = new Student();
student.setUsername("木心");
student.setPassword("123456");
Student student2 = new Student();
student2.setUsername("小白菜");
student2.setPassword("1234567");
JSONArray json = new JSONArray();
json.add(student);
json.add(student2);
return json;
}