json转换为键值对辅助类

  1 /// <summary>
  2 /// json转换为键值对辅助类
  3 /// </summary>
  4 public class JsonParser
  5 {
  6 
  7     private static Dictionary<string, string> lst_KeyValueData = null;
  8 
  9     public static Dictionary<string, string> SplitJsonStringToKeyValuePairs(string jsonStr)
 10     {
 11         char jsonBeginToken = '{';
 12         char jsonEndToken = '}';
 13 
 14         if (string.IsNullOrEmpty(jsonStr))
 15         {
 16             return null;
 17         }
 18         //验证json字符串格式
 19         if (jsonStr[0] != jsonBeginToken || jsonStr[jsonStr.Length - 1] != jsonEndToken)
 20         {
 21             throw new ArgumentException("非法的Json字符串!");
 22         }
 23 
 24         lst_KeyValueData = new Dictionary<string, string>();
 25 
 26         JObject jobj = new JObject();
 27 
 28         // 转换为json对象
 29         jobj = JObject.Parse(jsonStr);
 30         ParseJsonProperties(jobj);
 31 
 32         return lst_KeyValueData;
 33 
 34     }
 35 
 36 
 37     private static void ParseJsonProperties(JObject jObject)
 38     {
 39         IEnumerable<JProperty> jObject_Properties = jObject.Properties();
 40 
 41         JTokenType[] validPropertyValueTypes = { JTokenType.String, JTokenType.Integer, JTokenType.Float, JTokenType.Boolean, JTokenType.Null, JTokenType.Date, JTokenType.Bytes, JTokenType.Guid, JTokenType.Uri, JTokenType.TimeSpan };
 42         List<JTokenType> propertyTypes = new List<JTokenType>(validPropertyValueTypes);
 43 
 44         JTokenType[] validObjectTypes = { JTokenType.String, JTokenType.Array, JTokenType.Object };
 45         List<JTokenType> objectTypes = new List<JTokenType>(validObjectTypes);
 46 
 47        
 48 
 49         foreach (JProperty property in jObject_Properties)
 50         {
 51            
 52 
 53             try
 54             {
 55                 if (propertyTypes.Contains(property.Value.Type))
 56                 {
 57                     ParseJsonKeyValue(property, property.Name.ToString());
 58                 }
 59                 else if (objectTypes.Contains(property.Value.Type))
 60                 {
 61                     //Arrays ex. { names: ["first": "John", "last" : "doe"]}
 62                     if (property.Value.Type == JTokenType.Array && property.Value.HasValues)
 63                     {
 64                         ParseJsonArray(property);
 65                     }
 66 
 67                     //Objects ex. { name: "john"}
 68                     if (property.Value.Type == JTokenType.Object)
 69                     {
 70                         JObject jo = new JObject();
 71                         jo = JObject.Parse(property.Value.ToString());
 72                         string paramName = property.Name.ToString();
 73 
 74                         lst_KeyValueData.Add(paramName, property.Value.ToString());
 75 
 76                         if (jo.HasValues)
 77                         {
 78                             ParseJsonProperties(jo);
 79                         }
 80 
 81                     }
 82                 }
 83             }
 84             catch (Exception ex)
 85             {
 86                 throw;
 87             }
 88         } // End of ForEach
 89 
 90        
 91 
 92     }
 93 
 94     private static void ParseJsonKeyValue(JProperty item, string paramName)
 95     {
 96         lst_KeyValueData.Add(paramName, item.Value.ToString());
 97     }
 98 
 99     private static void ParseJsonArray(JProperty item)
100     {
101         JArray jArray = (JArray)item.Value;
102 
103         string paramName = item.Name.ToString();
104         lst_KeyValueData.Add(paramName, item.Value.ToString());
105 
106      
107 
108         try
109         {
110             for (int i = 0; i < jArray.Count; i++)
111             {
112 
113                 paramName = i.ToString();
114                 lst_KeyValueData.Add(paramName, jArray.Values().ElementAt(i).ToString());
115 
116                 JObject jo = new JObject();
117                 jo = JObject.Parse(jArray[i].ToString());
118                 IEnumerable<JProperty> jArrayEnum = jo.Properties();
119 
120                 foreach (JProperty jaItem in jArrayEnum)
121                 {
122                     var paramNameWithJaItem = jaItem.Name.ToString();
123 
124                     var itemValue = jaItem.Value.ToString(Formatting.None);
125                     if (itemValue.Length > 0)
126                     {
127                         switch (itemValue.Substring(0, 1))
128                         {
129                             case "[":
130                                 //Recusion call to itself
131                                 ParseJsonArray(jaItem);
132                                 break;
133                             case "{":
134                                 //Create a new JObject and parse
135                                 JObject joObject = new JObject();
136                                 joObject = JObject.Parse(itemValue);
137 
138                                 //For this value, reparse from the top
139                                 ParseJsonProperties(joObject);
140                                 break;
141                             default:
142                                 ParseJsonKeyValue(jaItem, paramNameWithJaItem);
143                                 break;
144                         }
145                     }
146                 }
147             } //end for loop
148 
149         }
150         catch (Exception ex)
151         {
152             throw;
153         }
154     }
155 }
原文地址:https://www.cnblogs.com/micro-chen/p/5916436.html