浅析JSON序列化与反序列化
方法一:引入system.web.script.serialization命名空间使用 javascriptserializer类实现简单的序列化序列化类:personnel
public class personnel
{
public int id { get; set; }
public string name { get; set; }
}
执行序列化反序列化:
protected void page_load(object sender, eventargs e)
{
personnel personnel = new personnel();
personnel.id = 1;
personnel.name = "小白";
javascriptserializer jsonserializer = new javascriptserializer();
//执行序列化
string r1 = jsonserializer.serialize(personnel);
//执行反序列化
personnel _personnel = jsonserializer.deserialize<personnel>(r1);
}
r1输出结果:{"id":1,"name":"小白"}
可以使用 scriptignore属性标记不序列化公共属性或公共字段。
public class personnel
{
[scriptignore]
public int id { get; set; }
public string name { get; set; }
}
r1输出结果:{"name":"小白"}
方法二:引入 system.runtime.serialization.json命名空间使用 datacontractjsonserializer类实现序列化
序列化类:people
public class people
{
public int id { get; set; }
public string name { get; set; }
}
执行序列化反序列化
protected void page_load(object sender, eventargs e)
{
people people = new people();
people.id = 1;
people.name = "小白";
datacontractjsonserializer json = new datacontractjsonserializer(people.gettype());
string szjson = "";
//序列化
using (memorystream stream = new memorystream())
{
json.writeobject(stream, people);
szjson = encoding.utf8.getstring(stream.toarray());
}
//反序列化
using (memorystream ms = new memorystream(encoding.utf8.getbytes(szjson)))
{
datacontractjsonserializer serializer = new datacontractjsonserializer(typeof(people));
people _people = (people)serializer.readobject(ms);
}
}
szjson输出结果:{"id":1,"name":"小白"}
可以使用ignoredatamember:指定该成员不是数据协定的一部分且没有进行序列化,datamember:定义序列化属性参数,使用datamember属性标记字段必须使用datacontract标记类 否则datamember标记不起作用。
[datacontract]
public class people
{
[datamember(name = "id")]
public int id { get; set; }
[ignoredatamember]
public string name { get; set; }
}
输出结果: {"id":1}