Three ways in which spring MVC returns JSON data

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.