在实际开发项目中,有时候会为Android开发团队提供一些接口,一般是以asmx文件的方式来承载。而公布出去的数据一般上都是标准的json数据。但是在实际过程中,发现Android团队那边并不是通过将JSON序列化成类对象来进行解析的(通过parse json数据来进行),所以我这里要提供以下我自己在实际项目中,使用的方法,以期起到抛砖引玉的作用。

我们先在.net端建立两个WebService对象:

首先,建立一个名称为GetPhoneUnCharged的对象,用来获取暂未充值完成的手机列表用户。

 1:    #region 总体说明:获取未发送的手机充值列表
 2:          [WebMethod(Description = "总体说明:获取未发送的手机充值列表")]
 3:          public string GetPhoneUnCharged()
 4:          {
 5:              using (var e = new brnmallEntities())
 6:              {
 7:                  var result = from p in e.cha_phonecharge where p.chargestateid == 1 select p;
 8:                  return JsonConvert.SerializeObject(result.ToList());
 9:              }
10:          }
11:          #endregion
12:  

从上面代码可以看出,我们返回的是被Newtonsoft.json组件序列化的json字符串数组。

我们从捕获的截图中,可以看到我们返回的JSON字符串数据:

然后,在.net中,我们创建如下的DTO对象:

 1:  public class cha_phonechargedto
 2:  {
 3:         public int phonechargeid { get; set; }
 4:         public int uid { get; set; }
 5:         public string chargephone { get; set; }
 6:         public DateTime? chargetime { get; set; }
 7:         public int chargestateid { get; set; }
 8:         public string chargestate { get; set; }
 9:         public decimal chagemoney { get; set; }
10:         public string chargememo { get; set; }
11:         public int chargetypeid { get; set; }
12:         public int serviceid { get; set; }
13:   
14:         public string username { get; set; } //用户名称
15:         public string chargetype { get; set; } //支付,还是缴费
16:         public string servicename { get; set; } //运营商名称
17:  
18:         public bool error { get; set; }
19:         public string message { get; set; }
20:     }
21:   

这个DTO对象主要就是返回一些用户数据以供Android客户端调用。

下面我们来添加我们的WebService方法:

 1:   #region 总体说明:手工缴费(兼容性放法)
 2:          [WebMethod(Description = "总体说明:手工缴费(兼容性放法)", MessageName = "ManualCharge")]
 3:          public string ManualCharge(string phonechargeid)
 4:          {
 5:              int phonechargeidInInt32;
 6:              if (string.IsNullOrEmpty(phonechargeid))
 7:                  return JsonConvert.SerializeObject(new cha_phonechargedto() { error = true, message = "缴费序号不能为空!" });
 8:              if (!Int32.TryParse(phonechargeid, out phonechargeidInInt32))
 9:                  return JsonConvert.SerializeObject(new cha_phonechargedto() { error = true, message = "缴费序号只能为数字型!" });
10:   
11:              using (var e = new brnmallEntities())
12:              {
13:                  var result = (from p in e.cha_phonecharge where p.phonechargeid == phonechargeidInInt32 select p).FirstOrDefault();
14:                  if (result == null)
15:                      return JsonConvert.SerializeObject(new cha_phonechargedto() { error = true, message = "未找到缴费记录!" });
16:                  else
17:                  {
18:                      //如果处于可以缴费的模式
19:                      if (result.chargestateid == 1)
20:                      {
21:                          result.chargestateid = 2; //缴费成功
22:                          result.chargememo = "于[" + DateTime.Now.ToString("yyyy年MM月dd日 hh:mm:ss") + "]自动缴费成功";
23:                          try
24:                          {
25:                              e.SaveChanges();
26:                              return JsonConvert.SerializeObject(new cha_phonechargedto() { error = false, message = "手工缴费成功!" });
27:                          }
28:                          catch (Exception ex)
29:                          {
30:                              return JsonConvert.SerializeObject(new cha_phonechargedto() { error = true, message = ex.Message });
31:                          }
32:                      }
33:                      else if (result.chargestateid == 2) //如果已经缴费,则无需重复缴费
34:                      {
35:                          result.chargememo = "于[" + DateTime.Now.ToString("yyyy年MM月dd日 hh:mm:ss") + "]有重复缴费行为,已被自动处理";
36:                      }
37:                      else  //其他未知原因,导致的不能缴费的情况
38:                      {
39:                          result.chargememo = "于[" + DateTime.Now.ToString("yyyy年MM月dd日 hh:mm:ss") + "]发现本记录异常,无法被自动缴费";
40:                      }
41:                  }
42:                  return JsonConvert.SerializeObject(new cha_phonechargedto() { error = true, message = "手工缴费成功!" });
43:              }
44:          }
45:          #endregion
46:  

这个方法最后返回的数据为String类型的标准的JSON数据。在返回值中,我已经利用Newtonsoft.json组件将对象转换成了标准的json数据。

以上就是.net WebService所有的内容了。我们再来看看Android端怎么进行的。

首先,我们需要下载两个用于json数据解析的jar包:gson-2.2.4.jar 和 ksoap2-android-assembly-2.4-jar-with-dependencies.jar,将其添加到libs目录下。

其次,我们需要在Android端,创建一个一模一样的DTO对象:cha_phonechargedto。

然后,开始编写解析代码如下:

  1:  public void run() {
  2:              System.out.println("Polling...");
  3:   
  4:              String nameSpace = "http://tempuri.org/";
  5:              String serviceURL = "http://******:8001/ChargeService.asmx";
  6:   
  7:              String methodName = "GetPhoneUnCharged";
  8:              String soapAction = "http://tempuri.org/GetPhoneUnCharged";
  9:              SoapObject request = new SoapObject(nameSpace, methodName);
 10:   
 11:              SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
 12:                      SoapEnvelope.VER11);
 13:              envelope.bodyOut = request;
 14:              envelope.dotNet = true;
 15:              HttpTransportSE ht = new HttpTransportSE(serviceURL);
 16:              ht.debug = false;
 17:              try {
 18:                  ht.call(soapAction, envelope);
 19:                  if (envelope.getResponse() != null) {
 20:                      String result = envelope.getResponse().toString();
 21:                      Log.d("result", result);
 22:   
 23:                      Gson gson = new Gson();
 24:                      List<cha_phonechargedto> ps = gson.fromJson(result,new TypeToken<List<cha_phonechargedto>>() {}.getType());
 25:   
 26:                      for (int i = 0; i < ps.size(); i++) {
 27:                          cha_phonechargedto p = ps.get(i);
 28:   
 29:                          String phone = p.getChargephone().toString(); // 电话号码
 30:                          String fee = p.getChagemoney().toString(); // 缴费金额
 31:                          String stuffID = p.getServiceid().toString(); // ServiceCompany  1:电信  2:移动 3:联通
 32:                          String phonechargeid = p.getPhonechargeid().toString();
 33:                          int feeEx= new Double(fee).intValue();
 34:   
 35:                          System.out.println(phone + "|" + fee + "|" + stuffID+ "|" + phonechargeid);
 36:   
 37:                          String messageDaemon = "";
 38:                          String messageTo = "";
 39:                          String smsCenterPhone = "";
 40:   
117:                          if (stuffID.equalsIgnoreCase("3")) // 联通 Send To 10011
118:                          {
119:                              messageDaemon = "××××××" + phone + "#" + feeEx;
120:                              messageTo = "10011";
121:                              smsCenterPhone = "13000000000";
122:                              Log.d("result", messageDaemon + "|" + messageTo + "|"+ smsCenterPhone);
123:   
124:                              String methodName1 = "ManualCharge";
125:                              String soapAction1 = "http://tempuri.org/ManualCharge";
126:                              SoapObject request1 = new SoapObject(nameSpace,methodName1);
127:                              // 如果有参数,可以加入,没有的话,则忽略
128:                              Log.d("phonechargeid", phonechargeid);
129:                              request1.addProperty("phonechargeid", phonechargeid);
130:   
131:                              SoapSerializationEnvelope envelope1 = new SoapSerializationEnvelope(SoapEnvelope.VER11);
132:                              envelope1.bodyOut = request1;
133:                              envelope1.dotNet = true;
134:   
135:                              ht.call(soapAction1, envelope1);
136:                              if (envelope1.getResponse() != null) {
137:                                  String operation = envelope1.getResponse().toString();
138:                                  Log.d("operation", operation);
139:   
140:                                  Gson gsonResponse = new Gson();
141:                                  cha_phonechargedto resultResponse = gsonResponse.fromJson(operation,new TypeToken<cha_phonechargedto>() {}.getType());
142:   
143:                                  boolean errorflag = resultResponse.getError();
144:   
145:                                  if(!errorflag) //can send message out 
146:                                   {
147:                                      // Send Message Out
148:                                      SmsManager smsManager = SmsManager.getDefault();
149:                                      smsManager.sendTextMessage(messageTo,smsCenterPhone, messageDaemon, null, null);
150:   
151:                                      Log.d("result", messageDaemon + " have sent");
152:                                  }
153:                              }
154:                          }
155:   
156:                          Thread.sleep(2000);
157:                      }
158:                  }
159:              } catch (Exception e) {
160:                  e.printStackTrace();
161:   
162:              }
163:          }
164:      }

首先,建立SoapObject来承载要Invoke的函数名称,然后通过Gson的fromJson方法,将WebService提供的JSON数据,序列化到List<cha_phonechargedto>对象中去。最后就是通过一系列的逻辑,来实现软件需要实现的目的。

其实说起来挺简单的。

但是也许有人会问,如果我不知道你们提供的cha_phonechargedto对象里面的内容,咋办呢? 其实很简单,网上已经有专门提供JSON数据类生成的服务了,我们可以拿好我们的json数据,直接去生成类去。

我们的json数据如下:

[
{
"$id": "1",
"phonechargeid": 1626,
"uid": 9,
"chargephone": "18239236557",
"chargetime": "2015-02-02T18:05:39.8",
"chargestateid": 1,
"chagemoney": 50,
"chargememo": "网页端手机充值",
"chargetypeid": 2,
"serviceid": 2,
"EntityKey": {
"$id": "2",
"EntitySetName": "cha_phonecharge",
"EntityContainerName": "brnmallEntities",
"EntityKeyValues": [
{
"Key": "phonechargeid",
"Type": "System.Int32",
"Value": "1626"
}
]
}
},
{
"$id": "3",
"phonechargeid": 1634,
"uid": 9,
"chargephone": "18239236557",
"chargetime": "2015-02-03T10:11:57.143",
"chargestateid": 1,
"chagemoney": 50,
"chargememo": "网页端手机充值",
"chargetypeid": 2,
"serviceid": 2,
"EntityKey": {
"$id": "4",
"EntitySetName": "cha_phonecharge",
"EntityContainerName": "brnmallEntities",
"EntityKeyValues": [
{
"Key": "phonechargeid",
"Type": "System.Int32",
"Value": "1634"
}
]
}
}
]

[
{
"$id": "1",
"phonechargeid": 1626,
"uid": 9,
"chargephone": "18239236557",
"chargetime": "2015-02-02T18:05:39.8",
"chargestateid": 1,
"chagemoney": 50,
"chargememo": "网页端手机充值",
"chargetypeid": 2,
"serviceid": 2,
"EntityKey": {
"$id": "2",
"EntitySetName": "cha_phonecharge",
"EntityContainerName": "brnmallEntities",
"EntityKeyValues": [
{
"Key": "phonechargeid",
"Type": "System.Int32",
"Value": "1626"
}
]
}
},
{
"$id": "3",
"phonechargeid": 1634,
"uid": 9,
"chargephone": "18239236557",
"chargetime": "2015-02-03T10:11:57.143",
"chargestateid": 1,
"chagemoney": 50,
"chargememo": "网页端手机充值",
"chargetypeid": 2,
"serviceid": 2,
"EntityKey": {
"$id": "4",
"EntitySetName": "cha_phonecharge",
"EntityContainerName": "brnmallEntities",
"EntityKeyValues": [
{
"Key": "phonechargeid",
"Type": "System.Int32",
"Value": "1634"
}
]
}
}
]

然后将上面数据拷贝到http://tools.wx6.org/json2csharp/这个网站中,点击生成按钮,可以生成如下的类对象:

 1:   
 2:   
 3:  public class EntityKeyValues
 4:  {
 5:      public string Key { get; set; }
 6:      public string Type { get; set; }
 7:      public int Value { get; set; }
 8:  }
 9:  public class EntityKey
10:  {
11:      public string EntitySetName { get; set; }
12:      public string EntityContainerName { get; set; }
13:      public List<EntityKeyValues> EntityKeyValues { get; set; }
14:  }
15:  public class Root
16:  {
17:      public int Phonechargeid { get; set; }
18:      public int Uid { get; set; }
19:      public long Chargephone { get; set; }
20:      public DateTime Chargetime { get; set; }
21:      public int Chargestateid { get; set; }
22:      public int Chagemoney { get; set; }
23:      public string Chargememo { get; set; }
24:      public int Chargetypeid { get; set; }
25:      public int Serviceid { get; set; }
26:      public EntityKey EntityKey { get; set; }
27:  }
28:   

看看,是不是很相似呢? 相信你把这些对象直接转变为java中的dto对象,该是很简单的了。

上面有多余字段,你可以不加某些属性,就可以过滤掉不想要的字段。

期望对你有用,谢谢。

Android调用基于.net的WebService的更多相关文章

  1. python发布及调用基于SOAP的webservice

    现如今面向服务(SOA)的架构设计已经成为主流,把公用的服务打包成一个个webservice供各方调用是一种非常常用的做法,而应用最广泛的则是基于SOAP协议和wsdl的webservice.本文讲解 ...

  2. 在Android中调用C#写的WebService(附源代码)

    由于项目中要使用Android调用C#写的WebService,于是便有了这篇文章.在学习的过程中,发现在C#中直接调用WebService方便得多,直接添加一个引用,便可以直接使用将WebServi ...

  3. Android调用C#的WebService

    Android调用C#写的WebService 学习自: http://www.cnblogs.com/kissazi2/p/3406662.html 运行环境 Win10 VS 2015 Andro ...

  4. Android调用WebService(转)

    Android调用WebService WebService是一种基于SOAP协议的远程调用标准,通过 webservice可以将不同操作系统平台.不同语言.不同技术整合到一块.在Android SD ...

  5. Android调用天气预报的WebService简单例子

    下面例子改自网上例子:http://express.ruanko.com/ruanko-express_34/technologyexchange5.html 不过网上这个例子有些没有说明,有些情况不 ...

  6. Android使用ksoap2调用C#中的webservice实现图像上传

    目录: 一. android使用ksoap2调用webservice 二. 异步调用 三. Android使用ksoap2调用C#中的webservice实现图像上传参考方法 四. 图像传输中Base ...

  7. android调用webservice接口获取信息

    我的有一篇博客上讲了如何基于CXF搭建webservice,service层的接口会被部署到tomcat上,这一篇我就讲一下如何在安卓中调用这些接口传递参数. 1.在lib中放入ksoap2的jar包 ...

  8. Android调用.net的webservice服务器接收参数为空的情况

    问题描述:安卓开发中,用Android调用.net开发的wenService时候,从Android客户端传递参数到服务器端,服务器端接收为空 解决方法: 1.设置envelope.dotNet = t ...

  9. Android客户端调用Asp.net的WebService

    Android客户端调用Asp.net的WebService 我来说两句 |2011-11-23 13:39:15 在Android端为了与服务器端进行通信有几种方法:1.Socket通信2.WCF通 ...

随机推荐

  1. windows phone(成语典籍游戏开发)

  2. layout_weight的使用说明

    近期学习了Mars老师的视频,看了十二课的有关layout_weight的讲解,就做了些总结. layout_weight用于分配剩余的布局空间. 首先,先看段代码,它定义了两个textview控件 ...

  3. C++中的常量折叠

    先看例子: #include <iostream> using namespace std; int main() { ; int * p = (int *)(&a); *p = ...

  4. 《只是为了好玩:Linux之父林纳斯自传》

    <只是为了好玩:Linux之父林纳斯自传> 基本信息 作者: (美)Linus Torvalds    David Diamond 译者: 陈少芸 出版社:人民邮电出版社 ISBN:978 ...

  5. Effective Java 06 Eliminate obsolete object references

    NOTE Nulling out object references should be the exception rather than the norm. Another common sour ...

  6. linux安装pylab

    在linux下就是一句话 sudo apt-get install python-matplotlib 该工具包含了pylab, numpy,scipy和matplotlib四个工具包 对matplo ...

  7. 烂泥:【解决】ubuntu使用远程NFS报错

    本文由秀依林枫提供友情赞助,首发于烂泥行天下. 今天在ubuntu系统上使用远程NFS,发现一直报错无法使用. 查看NFS挂载命令没有错误,命令如下: mount -t nfs 192.168.1.1 ...

  8. matchesSelector及低版本IE中对该方法的实现

    matchesSelector用来匹配dom元素是否匹配某css selector.它为一些高级方法的实现提供了基础支持,比如事件代理,parent, closest等. W3C在2006年就提出了该 ...

  9. 计算1到最大的n位十进制数 ——大数解决

    要求:输入一个数字n,按照顺序打印出从1到最大的n为十进制.比如输入3,则打印出1.2.3……一直到最大的3位数999 这个看起来好像很简单啊.巴拉巴拉,已经得出了下面的代码 /** * 注意: 错误 ...

  10. javascript原型Prototype

    在javaScript创建对象一文中提到过:用构造函数创建对象存在一个问题即同一构造函数的不同实例的相同方法是不一样的,所以我们用原型把构造函数中公共的属性和方法提取出来进行封装,达到让所有实例共享的 ...