DataContractJsonSerializer在System.Runtime.Serialization.Json命名空間下,.NET Framework 3.5包含在System.ServiceModel.Web.dll中,須要添加對其的引用;.NET Framework 4在System.Runtime.Serialization中。web
1.建立 JsonHelper類json
1 //JSON序列化和反序列化輔助類 2 public class JsonHelper 3 { 4 // JSON序列化 5 public static string JsonSerializer<T>(T t) 6 { 7 DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); 8 MemoryStream ms = new MemoryStream(); 9 ser.WriteObject(ms, t); 10 string jsonString = Encoding.UTF8.GetString(ms.ToArray()); 11 ms.Close(); 12 return jsonString; 13 } 14 15 //JSON反序列化 16 public static T JsonDeserialize<T>(string jsonString) 17 { 18 DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); 19 MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); 20 T obj = (T)ser.ReadObject(ms); 21 return obj; 22 } 23 24 }
2.建立web服務頁面,進行序列化,併發布到本地服務器,我本地發佈後的地址爲:服務器
http://localhost:8012/ceshi/WebService1.asmx?op=HaiHai併發
1 public class Person 2 { 3 public string Name { get; set; } 4 5 public int Age { get; set; } 6 } 7 8 [WebMethod] 9 public string HaiHai() 10 { 11 Person person = new Person(); 12 person.Name = "jack"; 13 person.Age =26; 14 string jsonstring = JsonHelper.JsonSerializer<Person>(person); 15 16 return jsonstring; 17 18 }
3.將接口發佈到本地IIS,而後根據接口的地址,獲取數據反序列化ide
1 using (WebService1SoapClient client = new WebService1SoapClient()) 2 { 3 string ss = client.HaiHai(); 4 Response.Write(ss); 5 // context.Response.Write(ss); 6 }