Java custom method transforms the JSON string submitted by the front end to the Jsonobject object

Source: Internet
Author: User
Tags string format

The front-end commits JSON string format data, and the Java backend receives the JSON string data through a custom method and translates it into a Jsonobject object, as the code is relegated to the Requestdata.java class:

public static Jsonobject Getrequestjsonobj (HttpServletRequest request) {InputStreamReader reader = null;    InputStream in = null;    String REQUSETSB = "";    StringBuffer sb = new StringBuffer ();        try {in = Request.getinputstream ();        reader = new InputStreamReader (in, "UTF-8");        char[] buffer = new char[1024];        int Len;        while (len = reader.read (buffer)) > 0) {sb.append (buffer, 0, Len);        }//system.out.println ("Request information:" + sb.tostring ());    REQUSETSB = Sb.tostring ();    } catch (Exception e) {e.printstacktrace ();            } finally {try {if (reader! = null) {reader.close ();        }} catch (IOException e) {e.printstacktrace ();            } try {if (in! = null) {in.close ();        }} catch (IOException e) {e.printstacktrace (); }} jsonobject Jsobj = Jsonobject.fromobject (requsetsb.tostring()); return jsobj;} public static Object Getrequestjsonobj (HttpServletRequest request, Class clazz) {Jsonobject Jsonobject = Getrequestjso    Nobj (Request);    Object obj = Jsonobject.tobean (Jsonobject, clazz); return obj;}

Called in the controller:

@RequestMapping ("/test") public void Test (HttpServletRequest request) {    Jsonobject obj = Requestdata.getrequestjsonobj (request);    String Usernameid = obj.getstring ("Usernameid");}

If you have an entity bean object, you can receive it in the following ways:

@RequestMapping ("/test") public void Test (HttpServletRequest request) {    User user = (user) Requestdata.getrequestjsonobj (Request, user.class);    String Usernameid = User.getusernameid ();}

Java custom method transforms the JSON string submitted by the front end to the Jsonobject object

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.