Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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