Json.NET读写Json文件(转)

Json文件的写入读取

采用的Json.NET提供的API。

http://james.newtonking.com/projects/json-net.aspx
http://www.codeplex.com/json/


以下是demo代码

[csharp]  view plain copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.IO;  
  8. using System.Text;  
  9. using Newtonsoft.Json;  
  10. using com.zjpx.model;  
  11. using System.Collections;  
  12. using Newtonsoft.Json.Converters;  
  13.   
  14. namespace web  
  15. {  
  16.     public partial class testJson : System.Web.UI.Page  
  17.     {  
  18.         protected void Page_Load(object sender, EventArgs e)  
  19.         {  
  20.             ConfigFileModel cfm = new ConfigFileModel();  //实体模型类  
  21.             cfm.CreateDate = "2012-02-23";  
  22.             cfm.FileName = "test.txt";  
  23.   
  24.             //可以操作集合  
  25.             Hashtable ht = new Hashtable();  
  26.             ht.Add("hs_name""alex");  
  27.             ht.Add("hs_pwd""ggg");  
  28.   
  29.             //序列化  
  30.             string js1 = JsonConvert.SerializeObject(cfm);  
  31.             string js2 = JsonConvert.SerializeObject(ht);  
  32.             Response.Write(js1);  
  33.             Response.Write("<br/>");  
  34.             Response.Write(js2);  
  35.             //"{\"FileName\":\"test.txt\",\"CreateDate\":\"2012-02-23\"}"  
  36.             //"{\"hs_pwd\":\"ggg\",\"hs_name\":\"alex\"}"  
  37.   
  38.             //反序列化  
  39.             ConfigFileModel debc1 = JsonConvert.DeserializeObject<ConfigFileModel>(js1);  
  40.             ConfigFileModel debc2 = JsonConvert.DeserializeObject<ConfigFileModel>(js2);  
  41.   
  42.             //找到服务器物理路径  
  43.             //string serverAppPath = Request.PhysicalApplicationPath.ToString();  
  44.             string serverAppPath = @"d:\";  
  45.             //构成配置文件路径  
  46.             string con_file_path =@""+ serverAppPath + @"config.json";  
  47.   
  48.   
  49.             if (!File.Exists(con_file_path))  
  50.             {  
  51.                 File.Create(con_file_path);  
  52.             }  
  53.   
  54.         //把模型数据写到文件  
  55.             using (StreamWriter sw = new StreamWriter(con_file_path))  
  56.             {  
  57.                 try  
  58.                 {  
  59.   
  60.                     JsonSerializer serializer = new JsonSerializer();  
  61.                     serializer.Converters.Add(new JavaScriptDateTimeConverter());  
  62.                     serializer.NullValueHandling = NullValueHandling.Ignore;  
  63.   
  64.                     //构建Json.net的写入流  
  65.                     JsonWriter writer = new JsonTextWriter(sw);  
  66.                     //把模型数据序列化并写入Json.net的JsonWriter流中  
  67.                     serializer.Serialize(writer, cfm);  
  68.                     //ser.Serialize(writer, ht);  
  69.                     writer.Close();  
  70.                     sw.Close();  
  71.   
  72.                 }  
  73.   
  74.         }  
  75.             catch (Exception ex)  
  76.             {  
  77.                 ex.Message.ToString();  
  78.             }  
  79.   
  80.              //读取json文件  
  81.              using (StreamReader sr = new StreamReader(con_file_path))  
  82.              {  
  83.           try  
  84.                   {  
  85.                       JsonSerializer serializer = new JsonSerializer();  
  86.                       serializer.Converters.Add(new JavaScriptDateTimeConverter());  
  87.                       serializer.NullValueHandling = NullValueHandling.Ignore;  
  88.   
  89.                       //构建Json.net的读取流  
  90.                       JsonReader reader = new JsonTextReader(sr);  
  91.                       //对读取出的Json.net的reader流进行反序列化,并装载到模型中  
  92.                       cfm = serializer.Deserialize<ConfigFileModel>(reader);  
  93.   
  94.                       Response.Write("<br/>");  
  95.                       Response.Write(cfm.FileName+", "+cfm.CreateDate);  
  96.           }  
  97.                   catch (Exception ex)  
  98.                   {  
  99.                       ex.Message.ToString();  
  100.                   }  
  101.               }  
  102.   
  103.         }  
  104.     }  
  105.   
  106.     public class ConfigFileModel  
  107.     {  
  108.         public ConfigFileModel() { }  
  109.   
  110.         string _fileName;  
  111.   
  112.         public string FileName  
  113.         {  
  114.             get { return _fileName; }  
  115.             set { _fileName = value; }  
  116.         }  
  117.         string _createDate;  
  118.   
  119.         public string CreateDate  
  120.         {  
  121.             get { return _createDate; }  
  122.             set { _createDate = value; }  
  123.         }  
  124.     }  
  125. }  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
在C#中,可以使用Json.NET库来读写JSON文件。首先,你需要在项目中引用Json.NET库。然后,你可以通过以下方法读取JSON文件和将数据写入JSON文件: 1. 读取JSON文件: - 首先,使用`File.Exists`方法检查文件是否存在。 - 然后,使用`File.ReadAllText`方法读取文件内容,并将其存储为一个字符串。 - 使用`JsonConvert.DeserializeObject<T>`方法将字符串反序列化为指定的类型(在这个例子中是`ReadJson`类)。 2. 将数据写入JSON文件: - 你可以创建一个用于存储数据的类(在这个例子中是`ReadJson`类)。 - 将数据赋值给该类的属性。 - 使用`JsonConvert.SerializeObject`方法将类对象序列化为JSON字符串。 - 使用`File.WriteAllText`方法将JSON字符串写入文件。 以下是一个示例代码,展示了如何读取和写入JSON文件: ```csharp // 读取JSON文件 private void ReadJsonFile(string fileName) { if (File.Exists(fileName)) { string json = File.ReadAllText(fileName); ReadJson data = JsonConvert.DeserializeObject<ReadJson>(json); // 对读取到的数据进行操作 // 这里是将数据展示在listBox1中 listBox1.Items.Add(AppDomain.CurrentDomain.BaseDirectory); this.y1_value = data.y1_value; this.y2_value = data.y2_value; this.y3_value = data.y3_value; this.y4_value = data.y4_value; this.y5_value = data.y5_value; this.y6_value = data.y6_value; this.y7_value = data.y7_value; this.y8_value = data.y8_value; this.y9_value = data.y9_value; List<List<int>> yValues = new List<List<int>>() { y1_value, y2_value, y3_value, y4_value, y5_value, y6_value, y7_value, y8_value, y9_value }; for (int i = 0; i < yValues.Count; i++) { string prefix = $"y{i + 1}"; string line = string.Join(" ", yValues[i]); listBox1.Items.Add($"{prefix}: {line}"); } } } // 写入JSON文件 private void WriteJsonFile(string fileName) { ReadJson data = new ReadJson() { y1_value = new List<int>() { 1, 2, 3 }, y2_value = new List<int>() { 4, 5, 6 }, y3_value = new List<int>() { 7, 8, 9 }, // 其他数据... }; string json = JsonConvert.SerializeObject(data); File.WriteAllText(fileName, json); } ``` 请注意,你需要根据自己的需求调整代码中的类和属性名称。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值