WebService and Android JSON data interaction mode settings in ASP.

Source: Internet
Author: User

First, server-side settings

1. Modify the Web. config

The system.web node inside the Web. config is added

<webServices>

<protocols>

<add name= "HttpPost"/>

<add name= "HttpGet"/>

</protocols>

</webServices>

2. Modify XX.asmx.cs

[WebService (Namespace = "http://tempuri.org/")]     [WebServiceBinding (ConformsTo = wsiprofiles.basicprofile1_1)]     [System.ComponentModel.ToolboxItem (False)] [System.Web.Script.Services.ScriptService]

At this point, the general function can return JSON data through code in Android, and the function that returns a DataTable cannot be

3. Function modification that returns a DataTable

A function is needed here to convert the DataTable to JSON format

  #region DataTable Conversion to JSON format        //             //DataTable conversion to JSON format              //            //             //              public string Datatablejson (DataTable dt)         {             StringBuilder jsonbuilder = new StringBuilder ();             Jsonbuilder.append ("{" ");             jsonbuilder.append (dt. Tablename.tostring ());             jsonbuilder.append ("": [");             for (int i = 0; i < dt. Rows.Count; i++)             {                 Jsonbuilder.append ("{");                 for (int j = 0; j < dt. Columns.count; J + +)                 {                     Jsonbuilder.append ("" ");                      Jsonbuilder.append (dt. COLUMNS[J]. ColumnName);                      Jsonbuilder.append ("": "");                     jsonbuilder.append (dt. ROWS[I][J]. ToString ());                      Jsonbuilder.append ("", ");                }                  Jsonbuilder.remove (Jsonbuilder.length- 1, 1);                 Jsonbuilder.append (" },");            }              Jsonbuilder.remove (jsonbuilder.length-1, 1);             jsonbuilder.append ("]");             jsonbuilder.append ("}");             return jsonbuilder.tostring ();        }

#endregion

Create a new function similar to the one that would otherwise need to return to the DataTable. Note here, be sure to write

[Scriptmethod (Responseformat = responseformat.xml)], or Android when acquiring data, the system will add a JSON of converted JSON data. Like what

 [webmethod]         [Scriptmethod (Responseformat = responseformat.xml)]         public string Hpreadqueryphone (string strSQL, string BD)          {            try              {                 MSQuery dbtable = new MSQuery ();                 DataSet dstable = Dbtable.hpreadquery (strSQL, BD);                 dbtable = null;                 if ( DsTable.Tables.Count = = 0)                  {&NBSP;&NBSP;&Nbsp;                 return "";                }                  Else                  {                     return Datatablejson (Dstable.tables[0]);                }             }              catch (System.Exception err)             {                 throwexception (ERR);                 return null;            }        }

Second, the Android code to wording

try{  string server_url = "Http://192.168.10.33:81/MobileService/MSServiceQuery.asmx/HPReadQueryPhone";    HttpPost request = new HttpPost (Server_url); Create an HTTP request based on the content source address              Request.addheader (" Content-type "," Application/json; Charset=utf-8 ");//You must add the HTTP header to return JSON data when WebMethod is called                        jsonobject jsonparams=new jsonobject ();          jsonparams.put ("Strdate", "1");          jsonparams.put ("AA", "1");          jsonparams.put ("strSQL", "SELECT * from Rruser");//Pass the parameter, If you want to pass two parameters, continue adding a second parameter jsonparams.put ("Param2name", "Param2value")          Jsonparams.put ("BD", "27");          httpentity bodyentity =neW stringentity (Jsonparams.tostring (), "UTF8");//The parameter must also be a string in JSON data format to be passed to the server side, otherwise "{' Message ': ' strUserName is invalid JSON primitive '} ' ERROR          log.i ("Ex", Jsonparams.tostring ());          request.setentity (bodyentity);          HttpResponse HttpResponse = new Defaulthttpclient (). Execute ( request); Send a request and get feedback          showmessage (Httpresponse.getstatusline (). ToString () );          if (Httpresponse.getstatusline (). Getstatuscode () ==200)           {                    String result = entityutils.tostring (httpresponse.getentity ());          log.i ("ex", result);          showmessage (Result);          if (!result.equals (""))          {           Try           {            jsonarray   jsonobjs = new Jsonobject (result) Getjsonarray ("Table");               Jsonobject jsonobj = ((jsonobject) jsonobjs.opt ( 0));                String username=jsonobj.getstring ("Usercname");                showmessage (username);

LOG.I ("Ex", String.valueof (Jsonobjs.length ()) + "AA");

} catch (Jsonexception e) {showmessage ("Data Error");          }}}} else {showmessage ("Network transmission error");   }} catch (Exception e) {log.i ("ex", E.getmessage ()); }

WebService and Android JSON data interaction mode settings in ASP.

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.