using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using com.zjpx.model;
using System.Collections;
using Newtonsoft.Json.Converters;
namespace web
{
public partial class testJson : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ConfigFileModel cfm = new ConfigFileModel(); //实体模型类
cfm.CreateDate = "2012-02-23";
cfm.FileName = "test.txt";
//可以操作集合
Hashtable ht = new Hashtable();
ht.Add("hs_name", "alex");
ht.Add("hs_pwd", "ggg");
//序列化
string js1 = JsonConvert.SerializeObject(cfm);
string js2 = JsonConvert.SerializeObject(ht);
Response.Write(js1);
Response.Write("<br/>");
Response.Write(js2);
//"{\"FileName\":\"test.txt\",\"CreateDate\":\"2012-02-23\"}"
//"{\"hs_pwd\":\"ggg\",\"hs_name\":\"alex\"}"
//反序列化
ConfigFileModel debc1 = JsonConvert.DeserializeObject<ConfigFileModel>(js1);
ConfigFileModel debc2 = JsonConvert.DeserializeObject<ConfigFileModel>(js2);
//找到服务器物理路径
//string serverAppPath = Request.PhysicalApplicationPath.ToString();
string serverAppPath = @"d:\";
//构成配置文件路径
string con_file_path =@""+ serverAppPath + @"config.json";
if (!File.Exists(con_file_path))
{
File.Create(con_file_path);
}
//把模型数据写到文件
using (StreamWriter sw = new StreamWriter(con_file_path))
{
try
{
JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new JavaScriptDateTimeConverter());
serializer.NullValueHandling = NullValueHandling.Ignore;
//构建Json.net的写入流
JsonWriter writer = new JsonTextWriter(sw);
//把模型数据序列化并写入Json.net的JsonWriter流中
serializer.Serialize(writer, cfm);
//ser.Serialize(writer, ht);
writer.Close();
sw.Close();
}
}
catch (Exception ex)
{
ex.Message.ToString();
}
//读取json文件
using (StreamReader sr = new StreamReader(con_file_path))
{
try
{
JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new JavaScriptDateTimeConverter());
serializer.NullValueHandling = NullValueHandling.Ignore;
//构建Json.net的读取流
JsonReader reader = new JsonTextReader(sr);
//对读取出的Json.net的reader流进行反序列化,并装载到模型中
cfm = serializer.Deserialize<ConfigFileModel>(reader);
Response.Write("<br/>");
Response.Write(cfm.FileName+", "+cfm.CreateDate);
}
catch (Exception ex)
{
ex.Message.ToString();
}
}
}
}
public class ConfigFileModel
{
public ConfigFileModel() { }
string _fileName;
public string FileName
{
get { return _fileName; }
set { _fileName = value; }
}
string _createDate;
public string CreateDate
{
get { return _createDate; }
set { _createDate = value; }
}
}
}
方法一:引入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}