写2个项目,一个console,一个web
调用方:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace ConsoleWSTest
{
class Program
{
static void Main(string[] args)
{
string url = "http://localhost:23978/TestEmpowerBinding.asmx";
string methodname = "Login";
//此处只需创建要传递的对象(单个对象、集合等),然后调用Json类进行转化
//暂时以自己拼凑出的json格式字符串为例(国、省、市)
/*************************************** Json格式传参的WebService调用 ***************************************/
string source = "{\"name\":\"中国\",\"province\":[{\"name\":\"黑龙江\",\"cities\":{\"city\":[\"哈尔滨\",\"大庆\"]}},{\"name\":\"广东\",\"cities\":{\"city\":[\"广州\",\"深圳\",\"珠海\"]}},{\"name\":\"台湾\",\"cities\":{\"city\":[\"台北\",\"高雄\"]}},{\"name\":\"新疆\",\"cities\":{\"city\":[\"乌鲁木齐\"]}}]}";
/*************************************** http的utf8转码 + json 格式的WebService调用***************************************/
string encodeSource = HttpUtility.UrlEncode(source, Encoding.UTF8);
/*************************************** http的utf8转码 + json 格式的WebService调用(zip压缩)***************************************/
encodeSource = ZipUtil.Compress(encodeSource);
WebServiceHelper.InvokeWebService(url, methodname, new object[] { encodeSource });
}
}
}
被调用方:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace TestWS
{
/// <summary>
/// WebService1 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
// [System.Web.Script.Services.ScriptService]
public class TestEmpowerBinding : System.Web.Services.WebService
{
[WebMethod]
public void Login(string source)
{
//解压缩
source = ZipUtil.Decompress(source);
//utf8转码
source = HttpUtility.UrlDecode(source, Encoding.UTF8);
//将转码后的json格式字符串转化为实体对象
China china = Json.JsonDeserializeByArrayData<China>(source);
//取出此实体对象中的值
string name = china.name;
foreach (Province province in china.province)
{
string p_name = province.name;
string[] city = province.cities.city;
}
}
}
}
China类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GDSService.Facade
{
public class China
{
public string name { get; set; }
public List<Province> province = new List<Province>();
}
public class Province
{
public string name { get; set; }
public Cities cities = new Cities();
}
public class Cities
{
public string[] city { get; set; }
}
}
WebServiceHelper类的地址:http://blog.csdn.net/config_man/article/details/16961151