C# Json序列化与反序列化

我们可以通过DataContractJsonSerializer类来序列化一个对象为json字符串

public class JsonConvert
	{
		public static string ObjectToJson(T obj)
		{
			var serializer = new DataContractJsonSerializer(typeof(T));
			var stream = new MemoryStream();
			serializer.WriteObject(stream, obj);

			byte[] dataBytes = new byte[stream.Length];

			stream.Position = 0;

			stream.Read(dataBytes, 0, (int)stream.Length);

			string json = Encoding.UTF8.GetString(dataBytes);

			return json;
		}

		public static T JsonToObject(string jsonString)
		{
			DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
			var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
			T t1 = (T)serializer.ReadObject(string);

			return t1;
		}
	}


 使用Json.NET(Newtonsoft.Json)进行序列化与反序列化

List students = studentBLL.GetALL();
            string jsonStudents = JsonConvert.SerializeObject(students);
 string jsonStudents = service.GetAllStudent();
            List students = JsonConvert.DeserializeObject>(jsonStudents);

学习资料:http://james.newtonking.com/json/help/index.html#

 

 

 

你可能感兴趣的:(C#)