Skip to content

Instantly share code, notes, and snippets.

@suyanhanx
Last active December 10, 2018 00:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suyanhanx/641c88db2f40eb7642d256ab0e306607 to your computer and use it in GitHub Desktop.
Save suyanhanx/641c88db2f40eb7642d256ab0e306607 to your computer and use it in GitHub Desktop.
transform a JObject to a Dictionary ( for IDictionary/IEnumerable)
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