json序列化和反序列化的使用教程
实体
public class wendaModel
{
private string _title;
private string _cons; public string title
{
set { _title = value; }
get { return _title; }
}
public string cons
{
set { _cons = value; }
get { return _cons; }
}
}
1、对象转换为json字符串(序列化)
wendaModel model = new wendaModel();
model.title = "json";
model.cons = "asp.net"; string json = Newtonsoft.Json.JsonConvert.SerializeObject(model);
Response.Write(json);
//输入结果:{"title":"json","cons":"asp.net"}
2、List转换为json字符串(序列化)
List<wendaModel> list = new List<wendaModel>();
for (int i = ; i < ; i++)
{
wendaModel model = new wendaModel();
model.title = "json" + i.ToString();
model.cons = "asp.net" + i.ToString();
list.Add(model);
}
string json = Newtonsoft.Json.JsonConvert.SerializeObject(list);
Response.Write(json);
//输出结果:[{"title":"json0","cons":"asp.net0"},{"title":"json1","cons":"asp.net1"},{"title":"json2","cons":"asp.net2"}]
3、json字符串转换为对象(反序列化)
string json = "{\"cons\":\"asp.net\",\"title\":\"json\"}";
wendaModel model = Newtonsoft.Json.JsonConvert.DeserializeObject<wendaModel>(json);
Response.Write(model.title + "=" + model.cons);
//输出结果:json=asp.net
4、json字符串转换为对象(反序列化)
string json = "[{\"cons\":\"asp.net2\",\"title\":\"json2\"},{\"cons\":\"asp.net1\",\"title\":\"json1\"}]";
List<wendaModel> list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<wendaModel>>(json);
foreach (var item in list)
{
Response.Write(item.title);
}