C# Parsing JSON Arrays

Posted by tmann on Tue, 01 Oct 2019 17:05:00 +0200

Links to the original text: https://www.cnblogs.com/chenyanbin/p/11200415.html

C# Parsing JSON Arrays

One way

Step 1: Before using, download: Newtonsoft.Json.dll

No, please come to me.

Link: https://pan.baidu.com/s/1JBkee4qhtW7XOyYFiGOL2Q
Extraction code: b5uq

Step 2: Introduce a namespace: using Newtonsoft.Json;

Step 3: Encapsulate a function for future use

JSON array to be parsed

 

Function:

1         public static Newtonsoft.Json.Linq.JArray GetToJsonList(string json)
2         {
3             Newtonsoft.Json.Linq.JArray jsonArr = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(json);
4             return jsonArr;
5         }

Realization:

 

Get it done.

Mode 2 (Recommendation):

The first step is to write the corresponding entity class according to this JSON. Used to store data. How is this entity class written? It's very simple. Because you don't need to write by hand, you can write it yourself if you like. But I usually use the website to convert directly. Take a look at it yourself, JSON to C# entity class, there will be many websites to transfer to you.

I use this website: http://www.bejson.com/convert/json2csharp/

 

{"message":"ok","nu":"367847964498","ischeck":"1","condition":"F00","com":"shunfeng","status":"200","state":"3","data":[{"time":"2017-09-21 09:33:09","ftime":"2017-09-21 09:33:09","context":"Already signed,Thank you for using Shunfeng.,Looking forward to serving you again","location":""},{"time":"2017-09-21 09:09:48","ftime":"2017-09-21 09:09:48","context":"Express to Gong Xiangtao, on the way to dispatch (contact number: 18806439871)","location":""},{"time":"2017-09-21 07:02:41","ftime":"2017-09-21 07:02:41","context":"The express arrives at the market of the market.","location":""},{"time":"2017-09-20 15:32:00","ftime":"2017-09-20 15:32:00","context":"The express has been loaded up at the business point of Xian City, Xian County Industrial Street, ready to send to the next station.","location":""},{"time":"2017-09-20 13:37:08","ftime":"2017-09-20 13:37:08","context":"Express mail to y. Xian Industrial Street business point.","location":""},{"time":"2017-09-20 10:47:07","ftime":"2017-09-20 10:47:07","context":"The express has been loaded into the next station.","location":""},{"time":"2017-09-20 10:15:47","ftime":"2017-09-20 10:15:47","context":"The express arrives at the new hi tech distribution center.","location":""},{"time":"2017-09-19 23:20:18","ftime":"2017-09-19 23:20:18","context":"The express has been loaded into the next station.","location":""},{"time":"2017-09-19 22:39:27","ftime":"2017-09-19 22:39:27","context":"The express arrives at the Shenzhen general distribution center.","location":""},{"time":"2017-09-19 18:57:33","ftime":"2017-09-19 18:57:33","context":"The express has been loaded to the next station in the Hualian community business department.","location":""},{"time":"2017-09-19 16:12:21","ftime":"2017-09-19 16:12:21","context":"I have received express mail.","location":""}]}

 

Simply put JSON on this website and automatically generate entity classes for us.

Entity class:

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace WindowsFormsApplication1
 7 {
 8 
 9     /// <summary>
10     /// Entity class of JSON data
11     /// </summary>
12     public class Root
13     {
14         /// <summary>
15         /// 
16         /// </summary>
17         public string message { get; set; }
18         /// <summary>
19         /// 
20         /// </summary>
21         public string nu { get; set; }
22         /// <summary>
23         /// 
24         /// </summary>
25         public string ischeck { get; set; }
26         /// <summary>
27         /// 
28         /// </summary>
29         public string condition { get; set; }
30         /// <summary>
31         /// 
32         /// </summary>
33         public string com { get; set; }
34         /// <summary>
35         /// 
36         /// </summary>
37         public string status { get; set; }
38         /// <summary>
39         /// 
40         /// </summary>
41         public string state { get; set; }
42         /// <summary>
43         /// 
44         /// </summary>
45         public List<DataItem> data { get; set; }
46     }
47     public class DataItem
48     {
49         /// <summary>
50         /// 
51         /// </summary>
52         public string time { get; set; }
53         /// <summary>
54         /// 
55         /// </summary>
56         public string ftime { get; set; }
57         /// <summary>
58         /// Thanks for using Shunfeng. We look forward to serving you again.
59         /// </summary>
60         public string context { get; set; }
61         /// <summary>
62         /// 
63         /// </summary>
64         public string location { get; set; }
65     }
66 
67 }

 

After the entity class is created, we also need a DLL file, Newtonsoft.Json.DLL. Look at the first way.

Encapsulating a Method

 

 1         /// <summary>
 2         /// Converting JSON to strings (including arrays)
 3         /// </summary>
 4         /// <typeparam name="T"></typeparam>
 5         /// <param name="json"></param>
 6         /// <returns></returns>
 7         public static T JsonConvertObject<T>(string json)
 8         {
 9             return JsonConvert.DeserializeObject<T>(json);
10         }

 

Call can

 

The following JSON help classes

 

  1 using System.Collections.Generic;
  2 using System.IO;
  3 using Newtonsoft.Json;
  4 using Newtonsoft.Json.Linq;
  5 using System.Data;
  6 using System.Reflection;
  7 using System;
  8 
  9 namespace Sam.OA.Common
 10 {
 11     /// <summary>
 12     /// Json Help Class
 13     /// Open source project libraries need to be referenced before use: Newtonsoft.Json.dll
 14     /// </summary>
 15     public sealed class JsonHelper
 16     {
 17         /// <summary>
 18         /// serialize objects into json format
 19         /// </summary>
 20         /// <param name="obj">serialized object </param>
 21         /// <returns>json string </returns>
 22         public static string SerializeObjct(object obj)
 23         {            
 24             return JsonConvert.SerializeObject(obj);
 25         }
 26         /// <summary>
 27         /// Parsing JSON Strings to Generate Object Entities
 28         /// </summary>
 29         /// <typeparam name="T">entity class </typeparam>
 30         /// <param name="json">JSON string </param>
 31         /// <returns></returns>
 32         public static T JsonConvertObject<T>(string json)
 33         {
 34             return JsonConvert.DeserializeObject<T>(json);
 35         }
 36         /// <summary>
 37         /// Parsing JSON Strings to Generate Object Entities
 38         /// </summary>
 39         /// <typeparam name="T">object type </typeparam>
 40         /// <param name="json">json string </param>
 41         /// <returns></returns>
 42         public static T DeserializeJsonToObject<T>(string json) where T:class
 43         {
 44             JsonSerializer serializer = new JsonSerializer();
 45             StringReader sr = new StringReader(json);
 46             object obj = serializer.Deserialize(new JsonTextReader(sr), typeof(T));
 47             T t = obj as T;
 48             return t;
 49         }
 50         /// <summary>
 51         /// Parsing JSON Array to Generate Object Entity Set
 52         /// </summary>
 53         /// <typeparam name="T">object type </typeparam>
 54         /// <param name="json">json array </param>
 55         /// < returns > object entity set </returns >
 56         public static List<T> DeserializeJsonToList<T>(string json) where T : class
 57         {
 58             JsonSerializer serializer = new JsonSerializer();
 59             StringReader sr = new StringReader(json);
 60             object obj = serializer.Deserialize(new JsonTextReader(sr), typeof(List<T>));
 61             List<T> list = obj as List<T>;
 62             return list;
 63         }
 64         /// <summary>
 65         /// Turn JSON into an array
 66         /// Usage: jsonArr[0]["xxxx"]
 67         /// </summary>
 68         /// <param name="json">json string </param>
 69         /// <returns></returns>
 70         public static JArray GetToJsonList(string json)
 71         {
 72             JArray jsonArr = (JArray)JsonConvert.DeserializeObject(json);
 73             return jsonArr;
 74         }
 75         /// <summary>
 76         /// Converting DataTable into Entity Classes
 77         /// </summary>
 78         /// <typeparam name="T">entity class </typeparam>
 79         /// <param name="dt">DataTable</param>
 80         /// <returns></returns>
 81         public static List<T> DtConvertToModel<T>(DataTable dt) where T : new()
 82         {
 83             List<T> ts = new List<T>();
 84             foreach (DataRow dr in dt.Rows)
 85             {
 86                 T t = new T();
 87                 foreach (PropertyInfo pi in t.GetType().GetProperties())
 88                 {
 89                     if (dt.Columns.Contains(pi.Name))
 90                     {
 91                         if (!pi.CanWrite) continue;
 92                         var value = dr[pi.Name];
 93                         if (value != DBNull.Value)
 94                         {
 95                             switch (pi.PropertyType.FullName)
 96                             {
 97                                 case "System.Decimal":
 98                                     pi.SetValue(t, decimal.Parse(value.ToString()), null);
 99                                     break;
100                                 case "System.String":
101                                     pi.SetValue(t, value.ToString(), null);
102                                     break;
103                                 case "System.Int32":
104                                     pi.SetValue(t, int.Parse(value.ToString()), null);
105                                     break;
106                                 default:
107                                     pi.SetValue(t, value, null);
108                                     break;
109                             }
110                         }
111                     }
112                 }
113                 ts.Add(t);
114             }
115             return ts;
116         }
117     }
118 }

 

 

Topics: JSON