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

107 阅读1分钟
  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

\