C#中用JavaScriptSerializer和Json.Net操作json格式的文件

1.json文件

2.写出对应的类

 1         //折扣
 2         public class Discount
 3         {
 4             public string Qty { get; set; }
 5             public string percentage { get; set; }
 6         }
 7         //产品信息
 8         public class ProductInfo
 9         {
10             public string packing { get; set; }
11             public string Qty { get; set; }
12             public List<Discount> Discount { get; set; }
13         }
14         //总信息
15         public class RootObject
16         {
17             public string id { get; set; }
18             public string date { get; set; }
19             public List<ProductInfo> productInfo { get; set; }
20         }
View Code

3.JavaScriptSerializer操作json

1             string jsonText = File.ReadAllText("JSON文件.json");
2             JavaScriptSerializer jss = new JavaScriptSerializer();
3             RootObject root = jss.Deserialize<RootObject>(jsonText);
4             Console.WriteLine(root.id + "==========" + root.date);
5             Console.WriteLine(root.productInfo[0].packing + "======" + root.productInfo[0].Qty);
6             Console.WriteLine(root.productInfo[0].Discount[0].Qty + "========" + root.productInfo[0].Discount[0].percentage);
7             Console.WriteLine(root.productInfo[0].Discount[1].Qty + "=======" + root.productInfo[0].Discount[1].percentage);
8             Console.ReadKey();
View Code

3.1运行结果

4.Json.Net操作json

1             string jsonText = File.ReadAllText("JSON文件.json");
2             //反序列化json字符串
3             RootObject root=JsonConvert.DeserializeObject<RootObject>(jsonText);
4             Console.WriteLine(root.id + "==========" + root.date);
5             Console.WriteLine(root.productInfo[0].packing + "======" + root.productInfo[0].Qty);
6             Console.WriteLine(root.productInfo[0].Discount[0].Qty + "========" + root.productInfo[0].Discount[0].percentage);
7             Console.WriteLine(root.productInfo[0].Discount[1].Qty + "=======" + root.productInfo[0].Discount[1].percentage);
8             Console.ReadKey();
View Code

4.1运行结果

4.2使用Json.Net序列化

1             Student stu=new Student();
2             stu.Id = 1;
3             stu.Name = "卡卡西";
4             stu.English = 85;
5             stu.Math = 100;
6             string jsonString=JsonConvert.SerializeObject(stu);
7             Console.WriteLine(jsonString);
8             Console.ReadKey();
View Code

原文地址:https://www.cnblogs.com/CSharpLover/p/5202051.html