json序列化
json的几种表现形式:
var user = {"name":"Manas","gender":"Male","birthday":"1987-8-8"} ;
var userlist = [{"user":{"name":"Manas","gender":"Male","birthday":"1987-8-8"}},
{"user":{"name":"Mohapatra","Male":"Female","birthday":"1987-7-7"}}];
var userlist = "{\"ID\":1,\"Name\":\"Manas\",\"Address\":\"India\"}"
json的序列化和反序列化:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
namespace json
{
[DataContract]
public class Student
{
[DataMember]
public int ID { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
[DataMember]
public string Sex { get; set; }
public void test()
{
Student st = new Student()
{
ID = 101,
Age = 10,
Name = "break",
Sex = "男"
};
#region 序列化对象的方式
DataContractJsonSerializer aj=new DataContractJsonSerializer(typeof(Student));
//内存流用于存放json格式
MemoryStream MS = new MemoryStream();
//将json写入到内存流中
aj.WriteObject(MS, st);
//在写入流的时候,流的位置会发生改变,所以这里需要将流的位置初始化
MS.Position = 0;
//读取流,将流转化为字符串。
StreamReader Sr = new StreamReader(MS,Encoding.UTF8);
string str = Sr.ReadToEnd();
Sr.Close();
MS.Close();
#endregion
#region 反序列化对象
string js = str;
//使用using,此范围操作完自动调用这个类实例的Dispose方法。
using(MemoryStream ms=new MemoryStream(Encoding.UTF8.GetBytes(str)))
{
//调用DataContractJsonSerializer的反序列化方法。
Student model=(Student)aj.ReadObject(ms);
Console.WriteLine(model.ID);
Console.WriteLine(model.Name);
Console.WriteLine(model.Age);
}
#endregion
Console.WriteLine(str);
Console.ReadKey();
}
//测试:
static void Main()
{
Student stu = new Student();
stu.test();
}
}
}
效果截图:
json在wpf中的运用:使用的时候,因为是静态类直接调用就可以了
using System; namespace CommonDLL /// <summary>
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); } /// <summary> |