Json文件讀寫
阿新 • • 發佈:2017-09-10
lex add name convert iter exce har 服務器 配置
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 [email protected]""+ 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; } } } }
Json文件讀寫