using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
using System.Xml.Linq;
using System.Text.Json;
using System.Collections;
namespace EasyDevCore.Common.Wrapper
{
///
///
///
public class DynamicJson : DynamicObject
{
private readonly IDictionary _dictionary;
///
/// Initializes a new instance of the class.
///
/// The json string.
private DynamicJson(string jsonString):this(JsonSerializer.Deserialize>(jsonString))
{
}
///
/// Initializes a new instance of the class.
///
/// The dictionary.
private DynamicJson(IDictionary dictionary)
{
_dictionary = dictionary;
}
///
/// Parses the specified XML string.
///
/// The json string.
///
public static DynamicJson Parse(string jsonString)
{
return new DynamicJson(jsonString);
}
///
/// Parses the specified dictionary.
///
/// The dictionary.
///
public static DynamicJson Parse(IDictionary dictionary)
{
return new DynamicJson(dictionary);
}
///
/// Loads the specified filename.
///
/// The filename.
///
public static DynamicJson Load(string filename)
{
return new DynamicJson(System.IO.File.ReadAllText(filename));
}
///
/// Provides the implementation for operations that get member values. Classes derived from the class can override this method to specify dynamic behavior for operations such as getting a value for a property.
///
/// Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member on which the dynamic operation is performed. For example, for the Console.WriteLine(sampleObject.SampleProperty) statement, where sampleObject is an instance of the class derived from the class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive.
/// The result of the get operation. For example, if the method is called for a property, you can assign the property value to .
///
/// if the operation is successful; otherwise, . If this method returns , the run-time binder of the language determines the behavior. (In most cases, a run-time exception is thrown.)
///
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (!_dictionary.TryGetValue(binder.Name, out result))
{
// return null to avoid exception. caller can check for null this way...
result = null;
return true;
}
result = WrapResultObject(result);
return true;
}
///
/// Wraps the result object.
///
/// The result.
///
private static object WrapResultObject(object result)
{
var dictionary = result as IDictionary;
if (dictionary != null)
return new DynamicJson(dictionary);
var arrayList = result as ArrayList;
if (arrayList != null && arrayList.Count > 0)
{
return arrayList[0] is IDictionary
? new List