asp.net中webservice与android的json数据交互方式设置

时间:2021-10-25 05:19:44

一 、服务器端设置

1.修改web.config

在web.config里面的的system.Web节点添加

<webServices>

<protocols>

<add name= "HttpPost"/>

<add name= "HttpGet"/>

</protocols>

</webServices>

2.修改XX.asmx.cs

[WebService(Namespace = "http://tempuri.org/")]     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]     [System.ComponentModel.ToolboxItem(false)]     [System.Web.Script.Services.ScriptService]

//至此,一般函数可在android中可以通过代码返回json数据,返回datatable的函数不可以

3.返回datatable的函数修改

此处需要用到一个函数将datatable转换成json格式

#region dataTable转换成Json格式         ///              /// dataTable转换成Json格式             ///              ///              ///              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

再将原本需要返回datatable的函数新建一个类似函数。此处注意,一定要写

[ScriptMethod(ResponseFormat = ResponseFormat.Xml)],不然android在获取数据时系统又会将转换好的json数据再加一层json。 比如

[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)                 {                     return "";                 }                 else                 {                     return DataTableJson(dsTable.Tables[0]);                 }             }             catch (System.Exception err)             {                 ThrowException(err);                 return null;             }         }

二、android代码写法

try{   String SERVER_URL = "http://192.168.10.33:81/MobileService/MSServiceQuery.asmx/HPReadQueryPhone";    HttpPost request = new HttpPost(SERVER_URL); // 根据内容来源地址创建一个Http请求             request.addHeader("Content-Type", "application/json; charset=utf-8");//必须要添加该Http头才能调用WebMethod时返回JSON数据                      JSONObject jsonParams=new JSONObject(); //         jsonParams.put("strdate", "1"); //         jsonParams.put("aa", "1");          jsonParams.put("strSql", "select * from RRUser");//传参,如果想传递两个参数则继续添加第二个参数jsonParams.put("param2Name","param2Value")          jsonParams.put("BD", "27");          HttpEntity bodyEntity =new StringEntity(jsonParams.toString(), "utf8");//参数必须也得是JSON数据格式的字符串才能传递到服务器端,否则会出现"{'Message':'strUserName是无效的JSON基元'}"的错误          Log.i("ex",jsonParams.toString());          request.setEntity(bodyEntity);          HttpResponse httpResponse = new DefaultHttpClient().execute(request); // 发送请求并获取反馈          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("数据错误");           }          }                 }          else          {           ShowMessage("网络传输错误");          }   }   catch(Exception e)   {    Log.i("ex", e.getMessage());   }