把JSON转换成键值对

  public static Dictionary<string, string> JsonStringToKeyValuePairs(string jsonStr) {
            char jsonBeginToken = '{';
            char jsonEndToken = '}';

            if (string.IsNullOrEmpty(jsonStr))
            {
                return null;
            }
            //验证json字符串格式
            if (jsonStr[0] != jsonBeginToken || jsonStr[jsonStr.Length - 1] != jsonEndToken)
            {
                throw new ArgumentException("非法的Json字符串!");
            }

            var resultDic = new Dictionary<string, string>();
            var jobj = JObject.Parse(jsonStr);
            JsonOn(jobj, resultDic);
            return resultDic;
        }
       private static Dictionary<string, string> JsonOn(JToken jobT, Dictionary<string, string> Dic)
        {
          
            //找出包含嵌套的字段列
            if (jobT is JObject jobj && jobj.Properties().Count() > 0)
            {
                foreach (var item in jobj.Properties())
                {
                   JsonProperties(item, Dic);
                }
            }
            else {
                Dic.Add(jobT.Path, jobT.ToString());

                return Dic;
            }
            return Dic;
        }
       private static Dictionary<string, string> JsonProperties(JProperty jobj, Dictionary<string, string> Dic) {
           return JsonOn(jobj.Value, Dic);
        }
原文地址:https://www.cnblogs.com/AnAng/p/10286423.html