C# DataContractJsonSerializer 处理Json
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.ServiceModel.Web; using System.IO; namespace Json1 { class Program { [DataContract(Namespace = "http://blog.csdn.net/longhaoyou")] public class JsonData { [DataMember(Order = 0)] public string id { get; set; } [DataMember(Order=1)] public string name { get; set; } } public static string JsonToString<T>(T value) { var vStream=new MemoryStream(); DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); serializer.WriteObject(vStream, value); byte[] jsondata = new byte[vStream.Length]; vStream.Position = 0; if (vStream.Read(jsondata, 0, jsondata.Length) != jsondata.Length) throw new Exception("读取出错"); return Encoding.UTF8.GetString(jsondata); } public static T StringToJson<T>(string text) { byte[] jsondata = Encoding.UTF8.GetBytes(text); DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); var vStream=new MemoryStream(jsondata); return (T)serializer.ReadObject(vStream); } static void Main(string[] args) { JsonData data = new JsonData() { id = "0001", name = "龙号友" }; string jsontext = JsonToString(data); Console.WriteLine(jsontext); data = StringToJson<JsonData>(jsontext); } } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。