One. Return Modelandview, which contains the map set
/** Returns the result of the Modelandview type * Checks the legality of the user name, returns False if the user already exists, otherwise returns True (returns the JSON data in the format {"Valid", true})*/@RequestMapping (Value= "/checknameexistsmethod2", produces = "application/json;charset=utf-8")//the produces value here is automatically determined by the return result if not set. Public@ResponseBody modelandview checkNameValidMethod2 (@RequestParam String name) {Booleanresult =true; //...map<string, boolean> map =NewHashmap<>(); Map.put ("Valid", result); return NewModelandview (NewMappingjackson2jsonview (), map); }
Two. Returns JSON of type string
/** Returns the result of string type * Check the legality of user name, return False if user already exists, otherwise return True (return JSON data, format {"Valid", true})*/@RequestMapping (Value= "/checknameexistsmethod1", produces = "Application/json;charset=utf-8") Public@ResponseBody string checkNameValidMethod1 (@RequestParam string name) {Booleanresult =true; //...Map.put ("valid", result); Objectmapper Mapper=NewObjectmapper (); String resultstring= ""; Try{resultstring=mapper.writevalueasstring (map); } Catch(jsonprocessingexception e) {e.printstacktrace (); } returnresultstring; }
Three. Returns the result of any predefined class type:
@RequestMapping (value = "/findemployeebyname") public @ResponseBody Employee Findemployeebyname (String name) { List<Employee> lstemployees = employeeservice.getallemployees ( ); for (Employee employee:lstemployees) { if (Employee.getname (). Equals (name)) return employee; } return NULL ; }
The employ here must be defined beforehand.
Three ways in which spring MVC returns JSON data