Spring MVC returns JSON data to the Android side

Source: Internet
Author: User
Tags gettext

When the original Android project, the server interface has been written by others, I call it, but the next project, the interface to do their own, I want to use the Spring MVC framework to provide interfaces, the two days to a dangerous the framework and how the framework returns JSON data. Here the two types of personal feel more convenient two methods (PS: In fact, I now only the two types).

1. Direct PrintWriter output JSON data

Using this method, you can put together a JSON string, but I do not agree with the method, after all, it is too easy to make mistakes. So here I'm going to build the Jsonobject object and print the object. First, we're going to import one of the most important jar packages.

Json-lib-2.2.2-jdk15.jar

Next we look at the code.

1  PackageSedion.zhr.controller;2 3 ImportJava.io.PrintWriter;4 5 Importjavax.servlet.http.HttpServletRequest;6 ImportJavax.servlet.http.HttpServletResponse;7 8 ImportNet.sf.json.JSONObject;9 Ten ImportOrg.springframework.stereotype.Controller; One Importorg.springframework.web.bind.annotation.RequestMapping; A  - @Controller -@RequestMapping ("/test") the  Public classTestController - { - /** - * Direct PrintWriter output JSON +      * @paramreq -      * @paramRep +      * @throwsException A      */ at@RequestMapping ("/login") -      Public voidGetjson (HttpServletRequest Req,httpservletresponse Rep)throwsException -     { -String username = req.getparameter ("username"); -String pass = req.getparameter ("Pass"); -          inSystem.out.println ("Direct printwriter output JSON:" +username + "--->" +pass); -  toPrintWriter writer =Rep.getwriter (); +Jsonobject Object =NewJsonobject (); -         if(Username.equals ("ZHR") && pass.equals ("123")) the         { *Object.put ("Results", "Login Success"); $         }Panax Notoginseng         Else -         { theObject.put ("Results", "Login Fail"); +         }         A          the writer.println (object.tostring ()); + Writer.flush (); - writer.close (); $          $     } -}

After the service is good, we simply do a test of the Android side, the interface is very simple, the code is not given.

The test code is as follows

1  Packagecom.example.jsontest;2 3 ImportOrg.json.JSONObject;4 ImportWebService. Webservice;5 ImportAndroid.annotation.SuppressLint;6 Importandroid.app.Activity;7 ImportAndroid.os.Bundle;8 ImportAndroid.os.Handler;9 ImportAndroid.os.Message;Ten ImportAndroid.view.Menu; One ImportAndroid.view.View; A ImportAndroid.view.View.OnClickListener; - ImportAndroid.widget.Button; - ImportAndroid.widget.EditText; the ImportAndroid.widget.Toast; -  -  Public classMainactivityextendsActivity - { +  -     PrivateEditText Edit_username,edit_pass; +     PrivateButton loginbtn; A     PrivateHandler Handler; at     PrivateJsonobject object; -      -@SuppressLint ("Handlerleak") - @Override -     protected voidonCreate (Bundle savedinstancestate) -     { in         Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.activity_main); toEdit_username =(EditText) Findviewbyid (r.id.username); +Edit_pass =(EditText) Findviewbyid (r.id.pass); -LOGINBTN =(Button) Findviewbyid (R.ID.LOGIN_BTN); the          *Handler =NewHandler () $         {Panax Notoginseng @Override -              Public voidhandlemessage (Message msg) the             { +                 if(Msg.what = = 123) AToast.maketext (Getapplicationcontext (), object.optstring ("Results"), Toast.length_short). Show ();; the  +             } -         }; $          $Loginbtn.setonclicklistener (NewOnclicklistener () -         { -              the @Override -              Public voidOnClick (View arg0) {Wuyi                  the                 NewThread (NewRunnable () -                 { Wu                      - @Override About                      Public voidRun () $                     { -Object =Webservice.login (Edit_username.gettext (). ToString (), Edit_pass.gettext (). ToString ()); -Message message =NewMessage (); -Message.what = 123; A handler.sendmessage (message); +                          the                     } - }). Start (); $                  the             } the         }); the          the          -     } in}

where the Webservice.login () method is my own encapsulated data submission method, specific details can be seen in my other blog Android submission data to the server-side method of simple encapsulation.

Let's test, enter the user name ZHR, password 123, you can see the console print out the direct printwriter output JSON:ZHR--->123 , indicating that the request, while the mobile phone also get the results returned

The test was successful.

2. Using spring built-in support

Use this method first to add the following configuration in SPRINGMVC

1 <Beanclass= "Org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">2  < Propertyname= "Messageconverters">3   <List>4    <Bean5     class= "Org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />6   </List>7  </ Property>8 </Bean>

Two jar packages are then introduced. Jackson-mapper-asl-1.8.5.jar and Jackson-core-asl-1.8.5.jar.

Then change the service-side code to

/*** Use spring built-in support *@paramreq *@paramRep *@throwsException*/@RequestMapping ("/login") @ResponseBody  PublicMap<string, string> Getjson (httpservletrequest req,httpservletresponse Rep)throwsException {String username= Req.getparameter ("username"); String Pass= Req.getparameter ("Pass"); System.out.println ("Using spring built-in support:" +username + "--->" +pass); Map<string, string> map =NewHashmap<string, string>(); if(Username.equals ("ZHR") && pass.equals ("123") {map.put ("Results", "Login Success"); }        Else{map.put ("Results", "Login Fail"); }                                returnmap; 

Remember to add @ResponseBody, this will support the return of complex objects, the Android side do not make any changes, test again.

Spring MVC returns JSON data to the Android side

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.