using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Runtime.Serialization; using System.IO; namespace JobSearch { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Product pro = new Product(); pro.Name = "show"; pro.Size = 70; pro.ProcductDate = DateTime.Now.AddDays(-10); IList<Product> ProductCollection = new List<Product>(); ProductCollection.Add(pro); ProductCollection.Add(pro); ProductCollection.Add(pro); string JsonStr = JsonConvert.SerializeObject(ProductCollection); //string JsonStr = JsonHelper.Serialize(ProductCollection); this.textBox1.Text = JsonStr; } private void button2_Click(object sender, EventArgs e) { string JsonStr = this.textBox1.Text; IList<Product> ProductCollection = (IList<Product>)JsonConvert.DeserializeObject(JsonStr, typeof(IList<Product>)); //Product pro = (Product)JsonConvert.DeserializeObject(JsonStr, typeof(Product)); MessageBox.Show(ProductCollection.Count.ToString()); } } [Serializable] public class Product { private string _Name = string.Empty; public string Name { get { return _Name; } set { _Name = value; } } private int _Size = 0; public int Size { get { return _Size; } set { _Size = value; } } private DateTime _ProcductDate = DateTime.MinValue; public DateTime ProcductDate { get { return _ProcductDate; } set { _ProcductDate = value; } } } public class JsonHelper { public static string Serialize<T>(T data) { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(data.GetType()); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, data); return Encoding.UTF8.GetString(ms.ToArray()); //ms.Position = 0; //using (StreamReader sr = new StreamReader(ms)) //{ // return sr.ReadToEnd(); //} } } public static T Deserialize<T>(string json) { T obj = Activator.CreateInstance<T>(); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType()); return (T)serializer.ReadObject(ms); } } } }