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); } } }
时间: 2024-11-02 23:32:51