我们可以通过DataContractJsonSerializer类来序列化一个对象为json字符串
public class JsonConvert<T>
{
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<Student> students = studentBLL.GetALL();
string jsonStudents = JsonConvert.SerializeObject(students);
string jsonStudents = service.GetAllStudent();
List<Student> students = JsonConvert.DeserializeObject<List<Student>>(jsonStudents);
学习资料:http://james.newtonking.com/json/help/index.html#