Last active
December 10, 2018 00:49
-
-
Save suyanhanx/641c88db2f40eb7642d256ab0e306607 to your computer and use it in GitHub Desktop.
transform a JObject to a Dictionary ( for IDictionary/IEnumerable)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Collections.Generic; | |
/// <summary> | |
/// JObject扩展 | |
/// </summary> | |
public static class JObjectExtensions | |
{ | |
/// <summary> | |
/// 将JObject转化成字典 | |
/// </summary> | |
/// <param name="json"></param> | |
/// <returns></returns> | |
public static IDictionary<string, object> ToDictionary(this JToken json) | |
{ | |
var propertyValuePairs = json.ToObject<Dictionary<string, object>>(); | |
ProcessJObjectProperties(propertyValuePairs); | |
ProcessJArrayProperties(propertyValuePairs); | |
return propertyValuePairs; | |
} | |
private static void ProcessJObjectProperties(IDictionary<string, object> propertyValuePairs) | |
{ | |
var objectPropertyNames = (from property in propertyValuePairs | |
let propertyName = property.Key | |
let value = property.Value | |
where value is JObject | |
select propertyName).ToList(); | |
objectPropertyNames.ForEach(propertyName => propertyValuePairs[propertyName] = ToDictionary((JObject)propertyValuePairs[propertyName])); | |
} | |
private static void ProcessJArrayProperties(IDictionary<string, object> propertyValuePairs) | |
{ | |
var arrayPropertyNames = (from property in propertyValuePairs | |
let propertyName = property.Key | |
let value = property.Value | |
where value is JArray | |
select propertyName).ToList(); | |
arrayPropertyNames.ForEach(propertyName => propertyValuePairs[propertyName] = ToArray((JArray)propertyValuePairs[propertyName])); | |
} | |
/// <summary> | |
/// 数据项转换到数组 | |
/// </summary> | |
/// <param name="array"></param> | |
/// <returns></returns> | |
public static object[] ToArray(this JArray array) | |
{ | |
return array.ToObject<object[]>().Select(ProcessArrayEntry).ToArray(); | |
} | |
private static object ProcessArrayEntry(object value) | |
{ | |
switch (value) | |
{ | |
case JObject _: | |
return ToDictionary((JObject)value); | |
case JArray _: | |
return ToArray((JArray)value); | |
default: | |
return value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment