首页 > 编程语言 > 详细

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

时间:2016-02-19 20:31:19      阅读:1006      评论:0      收藏:0      [点我收藏+]

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

技术分享

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

原文:http://www.cnblogs.com/CSharpLover/p/5202051.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!