VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • C#教程之C# Json.Net解析实例

本文以一个简单的小例子,简述Json.Net的相关知识,仅供学习分享使用,如有不足之处,还请指正。

概述

Json.Net is a Popular high-performance JSON framework for .NET. 

Json.Net是当前比较流行的高效的Json解析的.Net框架。主要支持序列化,反序列化,手动解析,Linq等功能,可谓是功能强大而使用简单。

  • 使用方式:在项目中引入Newtonsoft.Json.dll文件即可里面的功能。
  • 常见功能:序列化与反序列化
  • 常用的类:JsonConvert,JsonSerializerSettings,JValue , JArray , JObject , Formatting , JTokenWriter , JToken

效果图

具体如下图所示【序列化和反序列化】:

核心代码

序列化和反序列化的代码如下

复制代码
  1 public partial class JsonForm : Form
  2     {
  3         public JsonForm()
  4         {
  5             InitializeComponent();
  6         }
  7 
  8         /// <summary>
  9         /// 序列化对象
 10         /// </summary>
 11         /// <param name="sender"></param>
 12         /// <param name="e"></param>
 13         private void btnSerializeObject_Click(object sender, EventArgs e)
 14         {
 15             Person p = new Person()
 16             {
 17                 Name = "Hexiang",
 18                 Birthday = DateTime.Parse("2017-02-20 14:30:00"),
 19                 Gender = "",
 20                 Love = "Ball"
 21             };
 22             string strJson = JsonConvert.SerializeObject(p, Formatting.Indented);
 23             this.txtJson.Text = strJson;
 24         }
 25 
 26         /// <summary>
 27         /// 序列化字典
 28         /// </summary>
 29         /// <param name="sender"></param>
 30         /// <param name="e"></param>
 31         private void btnSerializeDictionary_Click(object sender, EventArgs e)
 32         {
 33             Dictionary<string, int> dicPoints = new Dictionary<string, int>(){
 34                 { "James", 9001 },
 35                 { "Jo", 3474 },
 36                 { "Jess", 11926 }
 37             };
 38 
 39             string strJson = JsonConvert.SerializeObject(dicPoints, Formatting.Indented);
 40 
 41             this.txtJson.Text = strJson;
 42 
 43         }
 44 
 45         /// <summary>
 46         /// 序列化List
 47         /// </summary>
 48         /// <param name="sender"></param>
 49         /// <param name="e"></param>
 50         private void btnSerializeList_Click(object sender, EventArgs e)
 51         {
 52             List<string> lstGames = new List<string>()
 53             {
 54                  "Starcraft",
 55                  "Halo",
 56                  "Legend of Zelda"
 57             };
 58 
 59             string strJson = JsonConvert.SerializeObject(lstGames);
 60 
 61             this.txtJson.Text = strJson;
 62         }
 63 
 64         /// <summary>
 65         /// 序列化到文件
 66         /// </summary>
 67         /// <param name="sender"></param>
 68         /// <param name="e"></param>
 69         private void btnSerializeToFile_Click(object sender, EventArgs e)
 70         {
 71             Person p = new Person()
 72             {
 73                 Name = "Hexiang",
 74                 Birthday = DateTime.Parse("2017-02-20 14:30:00"),
 75                 Gender = "",
 76                 Love = "Ball"
 77             };
 78             using (StreamWriter file = File.CreateText(@"d:\person.json"))
 79             {
 80                 JsonSerializer serializer = new JsonSerializer();
 81                 serializer.Serialize(file, p);
 82             }
 83         }
 84 
 85         /// <summary>
 86         /// 序列化枚举
 87         /// </summary>
 88         /// <param name="sender"></param>
 89         /// <param name="e"></param>
 90         private void btnSerializeEnum_Click(object sender, EventArgs e)
 91         {
 92             List<StringComparison> stringComparisons = new List<StringComparison>
 93             {
 94                  StringComparison.CurrentCulture,
 95                  StringComparison.Ordinal
 96              };
 97 
 98             string jsonWithoutConverter = JsonConvert.SerializeObject(stringComparisons);
 99 
100             this.txtJson.Text = jsonWithoutConverter;//序列化出来是枚举所代表的整数值
101 
102 
103             string jsonWithConverter = JsonConvert.SerializeObject(stringComparisons, new StringEnumConverter());
104             this.txtJson.Text += "\r\n";
105             this.txtJson.Text += jsonWithConverter;//序列化出来是枚举所代表的文本值
106             // ["CurrentCulture","Ordinal"]
107 
108             List<StringComparison> newStringComparsions = JsonConvert.DeserializeObject<List<StringComparison>>(
109                jsonWithConverter,
110                 new StringEnumConverter());
111         }
112 
113         /// <summary>
114         /// 序列化DataSet
115         /// </summary>
116         /// <param name="sender"></param>
117         /// <param name="e"></param>
118         private void btnSerializeDataSet_Click(object sender, EventArgs e)
119         {
120             DataSet dataSet = new DataSet("dataSet");
121             dataSet.Namespace = "NetFrameWork";
122             DataTable table = new DataTable();
123             DataColumn idColumn = new DataColumn("id", typeof(int));
124             idColumn.AutoIncrement = true;
125 
126             DataColumn itemColumn = new DataColumn("item");
127             table.Columns.Add(idColumn);
128             table.Columns.Add(itemColumn);
129             dataSet.Tables.Add(table);
130 
131             for (int i = 0; i < 2; i++)
132             {
133                 DataRow newRow = table.NewRow();
134                 newRow["item"] = "item " + i;
135                 table.Rows.Add(newRow);
136             }
137 
138             dataSet.AcceptChanges();
139 
140             string json = JsonConvert.SerializeObject(dataSet, Formatting.Indented);
141             this.txtJson.Text = json;
142         }
143 
144         /// <summary>
145         /// 序列化JRaw
146         /// </summary>
147         /// <param name="sender"></param>
148         /// <param name="e"></param>
149         private void btnSerializeRaw_Click(object sender, EventArgs e)
150         {
151             JavaScriptSettings settings = new JavaScriptSettings
152             {
153                 OnLoadFunction = new JRaw("OnLoad"),
154                 OnUnloadFunction = new JRaw("function(e) { alert(e); }")
155             };
156 
157             string json = JsonConvert.SerializeObject(settings, Formatting.Indented);
158 
159             this.txtJson.Text = json;
160 
161         }
162 
163         /// <summary>
164         /// 反序列化List
165         /// </summary>
166         /// <param name="sender"></param>
167         /// <param name="e"></param>
168         private void btnDeserializeList_Click(object sender, EventArgs e)
169         {
170             string json = @"['Starcraft','Halo','Legend of Zelda']";
171             List<string> videogames = JsonConvert.DeserializeObject<List<string>>(json);
172             this.txtJson.Text = string.Join(", ", videogames.ToArray());
173         }
174 
175         /// <summary>
176         /// 反序列化字典
177         /// </summary>
178         /// <param name="sender"></param>
179         /// <param name="e"></param>
180         private void btnDeserializeDictionary_Click(object sender, EventArgs e)
181         {
182             string json = @"{
183               'href': '/account/login.aspx',
184               'target': '_blank'
185              }";
186 
187             Dictionary<string, string> dicAttributes = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
188 
189             this.txtJson.Text = dicAttributes["href"];
190             this.txtJson.Text += "\r\n";
191             this.txtJson.Text += dicAttributes["target"];
192 
193 
194         }
195 
196         /// <summary>
197         /// 反序列化匿名类
198         /// </summary>
199         /// <param name="sender"></param>
200         /// <param name="e"></param>
201         private void btnDeserializeAnaymous_Click(object sender, EventArgs e)
202         {
203             var definition = new { Name = "" };
204 
205             string json1 = @"{'Name':'James'}";
206             var customer1 = JsonConvert.DeserializeAnonymousType(json1, definition);
207             this.txtJson.Text = customer1.Name;
208             this.txtJson.Text += "\r\n";
209 
210             string json2 = @"{'Name':'Mike'}";
211             var customer2 = JsonConvert.DeserializeAnonymousType(json2, definition);
212             this.txtJson.Text += customer2.Name;
213 
214         }
215 
216         /// <summary>
217         /// 反序列化DataSet
218         /// </summary>
219         /// <param name="sender"></param>
220         /// <param name="e"></param>
221         private void btnDeserializeDataSet_Click(object sender, EventArgs e)
222         {
223             string json = @"{
224                'Table1': [
225                  {
226                   'id': 0,
227                   'item': 'item 0'
228                  },
229                  {
230                    'id': 1,
231                   'item': 'item 1'
232                 }
233               ]
234             }";
235 
236             DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(json);
237 
238             DataTable dataTable = dataSet.Tables["Table1"];
239             this.txtJson.Text = dataTable.Rows.Count.ToString();
240 
241 
242             foreach (DataRow row in dataTable.Rows)
243             {
244                 this.txtJson.Text += "\r\n";
245                 this.txtJson.Text += (row["id"] + " - " + row["item"]);
246             }
247 
248         }
249 
250         /// <summary>
251         /// 从文件反序列化
252         /// </summary>
253         /// <param name="sender"></param>
254         /// <param name="e"></param>
255         private void btnDeserializeFrmFile_Click(object sender, EventArgs e)
256         {
257             using (StreamReader file = File.OpenText(@"d:\person.json"))
258             {
259                 JsonSerializer serializer = new JsonSerializer();
260                 Person p = (Person)serializer.Deserialize(file, typeof(Person));
261                 this.txtJson.Text = p.Name;
262             }
263         }
264 
265         /// <summary>
266         /// 反序列化带构造函数人类
267         /// </summary>
268         /// <param name="sender"></param>
269         /// <param name="e"></param>
270         private void btnDeserializeConstructor_Click(object sender, EventArgs e)
271         {
272             string json = @"{'Url':'http://www.google.com'}";
273 
274             //直接序列化会报错,需要设置JsonSerializerSettings中ConstructorHandling才可以。
275             Website website = JsonConvert.DeserializeObject<Website>(json, new JsonSerializerSettings
276             {
277                 ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
278             });
279 
280             this.txtJson.Text = website.Url;
281 
282         }
283 
284         /// <summary>
285         /// 反序列化对象,如果有构造函数中,创建对象,则用Json的进行替换
286         /// </summary>
287         /// <param name="sender"></param>
288         /// <param name="e"></param>
289         private void btnDeserializeObjectCreation_Click(object sender, EventArgs e)
290         {
291             //
292             string json = @"{
293                'Name': 'James',
294                'Offices': [
295                  'Auckland',
296                  'Wellington',
297                  'Christchurch'
298                ]
299              }";
300 
301             UserViewModel model1 = JsonConvert.DeserializeObject<UserViewModel>(json);
302 
303             this.txtJson.Text = string.Join(",", model1.Offices);//默认会重复
304             this.txtJson.Text += "\r\n";
305 
306             //每次从Json中创建新的对象
307             UserViewModel model2 = JsonConvert.DeserializeObject<UserViewModel>(json, new JsonSerializerSettings
308             {
309                 ObjectCreationHandling = ObjectCreationHandling.Replace
310             });
311 
312             this.txtJson.Text = string.Join(",", model2.Offices);
313 
314         }
315 
316         /// <summary>
317         /// 序列化默认值处理,没有赋值的则不序列化出来
318         /// </summary>
319         /// <param name="sender"></param>
320         /// <param name="e"></param>
321         private void btnSerializeDefautValue_Click(object sender, EventArgs e)
322         {
323             Person person = new Person();
324 
325             string jsonIncludeDefaultValues = JsonConvert.SerializeObject(person, Formatting.Indented);
326 
327             this.txtJson.Text=(jsonIncludeDefaultValues);//默认的序列化,带不赋值的属性
328 
329             this.txtJson.Text += "\r\n";
330 
331             string jsonIgnoreDefaultValues = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
332             {
333                 DefaultValueHandling = DefaultValueHandling.Ignore //去掉不赋值的属性
334             });
335 
336             this.txtJson.Text+=(jsonIgnoreDefaultValues);
337         }
338 
339         /// <summary>
340         /// 如果实体类中没有对应属性,则如何处理
341         /// </summary>
342         /// <param name="sender"></param>
343         /// <param name="e"></param>
344         private void btnDeserializeMissingMember_Click(object sender, EventArgs e)
345         {
346             string json = @"{
347                'FullName': 'Dan Deleted',
348                'Deleted': true,
349                'DeletedDate': '2013-01-20T00:00:00'
350              }";
351 
352             try
353             {
354                 JsonConvert.DeserializeObject<Account>(json, new JsonSerializerSettings
355                 {
356                     MissingMemberHandling = MissingMemberHandling.Error //要么忽略,要么报错
357                 });
358             }
359             catch (JsonSerializationException ex)
360             {
361                 this.txtJson.Text=(ex.Message);
362                 // Could not find member 'DeletedDate' on object of type 'Account'. Path 'DeletedDate', line 4, position 23.
363             }
364         }
365 
366         /// <summary>
367         /// 序列化时Null值的处理
368         /// </summary>
369         /// <param name="sender"></param>
370         /// <param name="e"></param>
371         private void btnSerializeNull_Click(object sender, EventArgs e)
372         {
373             Person person = new Person
374             {
375                 Name = "Nigal Newborn"
376             };
377 
378             //默认的序列化
379             string jsonIncludeNullValues = JsonConvert.SerializeObject(person, Formatting.Indented);
380 
381             this.txtJson.Text=(jsonIncludeNullValues);
382             this.txtJson.Text += "\r\n";
383 
384             //去掉Null值的序列化
385             string jsonIgnoreNullValues = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
386             {
387                 NullValueHandling = NullValueHandling.Ignore //可以忽略,可以包含
388             });
389 
390            this.txtJson.Text+=(jsonIgnoreNullValues);
391            
392         }
393 
394         /// <summary>
395         /// 序列化日期格式
396         /// </summary>
397         /// <param name="sender"></param>
398         /// <param name="e"></param>
399         private void btnSerializeDateTime_Click(object sender, EventArgs e)
400         {
401             DateTime mayanEndOfTheWorld = new DateTime(2012, 12, 21);
402 
403             string jsonIsoDate = JsonConvert.SerializeObject(mayanEndOfTheWorld);
404 
405             this.txtJson.Text = (jsonIsoDate);
406