|
|
using Newtonsoft.Json.Linq;
|
using System.Collections.Generic;
|
using System.Linq;
|
namespace CommonBase
|
{
|
/// <summary>
|
/// JObject扩展
|
/// </summary>
|
public static class JObjectExtensions
|
{
|
/// <summary>
|
/// 将JObject转化成字典
|
/// </summary>
|
/// <param name="json"></param>
|
/// <returns></returns>
|
public static dict Todict(this JToken json)
|
{
|
var propertyValuePairs = json.ToObject<dict>();
|
ProcessJObjectProperties(propertyValuePairs);
|
ProcessJArrayProperties(propertyValuePairs);
|
return propertyValuePairs;
|
}
|
|
private static void ProcessJObjectProperties(dict 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] = Todict((JObject)propertyValuePairs[propertyName]));
|
}
|
|
private static void ProcessJArrayProperties(dict 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]));
|
arrayPropertyNames.ForEach(propertyName => propertyValuePairs[propertyName] = ToList((JArray)propertyValuePairs[propertyName]));
|
}
|
|
/// <summary>
|
///
|
/// </summary>
|
/// <param name="array"></param>
|
/// <returns></returns>
|
public static object[] ToArray(this JArray array)
|
{
|
return array.ToObject<dynamic[]>().Select(ProcessArrayEntry).ToArray();
|
}
|
public static List<object> ToList(this JArray array)
|
{
|
return array.ToObject<dynamic[]>().Select(ProcessArrayEntry).ToList();
|
}
|
|
private static dynamic ProcessArrayEntry(dynamic value)
|
{
|
if (value is JObject)
|
{
|
return Todict((JObject)value);
|
}
|
if (value is JArray)
|
{
|
return ToList((JArray)value);
|
//return ToArray((JArray)value);
|
}
|
return value;
|
}
|
|
}
|
}
|