C#(.NET) Webservice返回json设置

68 篇文章 0 订阅
15 篇文章 0 订阅
 

一 、服务器端设置

   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格式

 #regiondataTable转换成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 = newHttpPost(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 * fromRRUser");//传参,如果想传递两个参数则继续添加第二个参数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 = newDefaultHttpClient().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 = newJSONObject(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());
  }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值