您当前的位置: 首页 >  c#

彭世瑜

暂无认证

  • 2浏览

    0关注

    2791博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

C#编程-101:读写Json文件示例

彭世瑜 发布时间:2017-08-06 22:02:33 ,浏览量:2

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Web.Script.Serialization;
  6. using System.IO;
  7. using Newtonsoft.Json;
  8.  
  9. namespace JsonTest
  10. {
  11.     class Person
  12.     {
  13.         public string name { get; set; }
  14.         public int age { get; set; }
  15.         public override string ToString()
  16.         {
  17.             return String.Format("Name : {0}\nAge : {1}",name,age);
  18.         }
  19.     }
  20.     class Program
  21.     {
  22.         static void Main(string[] args)
  23.         {
  24.              
  25.              
  26.             //方法一:
  27.             //Serialization class
  28.              !important;">;
  29.             //deserialize json from file
  30.             string Jsonsting = File.ReadAllText("Json.json");           
  31.             Person p1 = ser.Deserialize(Jsonsting);
  32.             Console.WriteLine(p1);
  33.  
  34.             //output json file
  35.             Person p2 = new Person() {name="ben",age=23 };
  36.             string outputJson = ser.Serialize(p2);
  37.             File.WriteAllText("output.json",outputJson);
  38.  
  39.             //方法二:
  40.             //Newtonsoft.Json --->Json.NET library
  41.             //deserialize json from file
  42.             string Jsonsting1 = File.ReadAllText("Json.json");            
  43.             Person p3 = JsonConvert.DeserializeObject(Jsonsting1);
  44.             Console.WriteLine(p1);
  45.  
  46.             //output json file
  47.             Person p4 = new Person() { name = "ben", age = 23 };
  48.             string outputJson1 = JsonConvert.SerializeObject(p4);
  49.             File.WriteAllText("output1.json", outputJson1);
  50.  
  51.             Console.ReadKey();
  52.  
  53.  
  54.         }
  55.     }
  56. }
备注:
(1)Serialization类需要引用: System.Web.Extensions
(2) Newtonsoft.Json类,需要在Nuget中安装json.net
关注
打赏
1665367115
查看更多评论
立即登录/注册

微信扫码登录

0.2515s