C# json 嵌套 排序 生成签名

  • json排序并取值
 1         static void Main(string[] args)
 2         {            
 3             var jsonStr = "json字符串";
 4             var jo = JObject.Parse(jsonStr);
 5             //var target = KeySort(jo);//排序
 6             var s = string.Join("", GetValue(jo));
 7             Console.WriteLine(s);
 8             Console.Read();
 9         }
10 
11         /// <summary>
12         /// json 排序并取值
13         /// </summary>
14         /// <param name="jo">JObject</param>
15         /// <returns></returns>
16         static List<string> GetValue(object jo)
17         {
18             var res = new List<string>();
19             var sd = new SortedDictionary<string, object>();
20             switch (jo.GetType().Name)
21             {
22                 case "JValue":
23                     res.Add(string.Format("{0}", (jo as JValue).Value));
24                     break;
25                 case "JObject":
26                     foreach (var x in jo as JObject)
27                     {
28                         sd.Add(x.Key, x.Value);
29                     }
30                     foreach (var x in sd)
31                     {
32                         res.Add(x.Key);//只取排序后的值需注释掉
33                         res.AddRange(GetValue(x.Value));
34                     }
35                     break;
36                 case "JArray":
37                     foreach (var x in jo as JArray)
38                     {
39                         res.AddRange(GetValue(x));
40                     }
41                     break;
42             }
43             return res;
44         }
45 
46         /// <summary>
47         /// json 排序
48         /// </summary>
49         /// <param name="jo">JObject</param>
50         /// <returns></returns>
51         static SortedDictionary<string, object> KeySort(JObject obj)
52         {
53             var res = new SortedDictionary<string, object>();
54             foreach (var x in obj)
55             {
56                 if (x.Value is JValue) res.Add(x.Key, x.Value);
57                 else if (x.Value is JObject) res.Add(x.Key, KeySort((JObject)x.Value));
58                 else if (x.Value is JArray)
59                 {
60                     var tmp = new SortedDictionary<string, object>[x.Value.Count()];
61                     for (var i = 0; i < x.Value.Count(); i++)
62                     {
63                         tmp[i] = KeySort((JObject)x.Value[i]);
64                     }
65                     res.Add(x.Key, tmp);
66                 }
67             }
68             return res;
69         }

 

posted @ 2018-07-30 01:15  gygang  阅读(1705)  评论(0编辑  收藏  举报