首先,第一点,通过 public object this[string name]
处理字典值,其次利用 DynamicObject
转换动态类。
参考:动态类型
/// <summary> /// 动态js类 /// </summary> [JsonConverter(typeof(DynamicJsJsonConverter))] public class DynamicJS : DynamicObject { private readonly Dictionary<string, object> dic = new Dictionary<string, object>(); private readonly bool _ignoreCase; /// <summary> /// 动态js类 /// </summary> /// <param name="ignoreCase">忽略大小写</param> public DynamicJS(bool ignoreCase = false) { _ignoreCase = ignoreCase; } public int Count { get => dic.Count; } public object this[string name] { get { name = _ignoreCase ? name.ToLower() : name; if (dic.TryGetValue(name, out object value)) { return value; } return null; } set { name = _ignoreCase ? name.ToLower() : name; dic[name] = value; } } public override bool TryGetMember(GetMemberBinder binder, out object result) { string name = _ignoreCase ? binder.Name.ToLower() : binder.Name; return dic.TryGetValue(name, out result); } public override bool TrySetMember(SetMemberBinder binder, object value) { string name = _ignoreCase ? binder.Name.ToLower() : binder.Name; dic[name] = value; return true; } /// <summary> /// 重写json序列化 /// </summary> /// <returns></returns> public override string ToString() { return JsonConvert.SerializeObject(dic); } public Dictionary<string, object> Value { get => dic; } } public class DynamicJsJsonConverter : JsonConverter { public override bool CanConvert(Type objectType) { throw new NotImplementedException(); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var result = ""; if (value is System.Dynamic.DynamicObject) { result = value.ToString(); } writer.WriteRaw(result); } }
class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); dynamic dynamicJS = new DynamicJS(); dynamicJS["AA"] = "aaaa"; dynamicJS.a = 11; dynamicJS.List = new List<int> { 123, 555, 666 }; Console.WriteLine(JsonConvert.SerializeObject(dynamicJS)); } }