zoukankan      html  css  js  c++  java
  • Json转化为动态变量

    public void JsonDemo()
    {
    string strJson = "{"count":"5550","status": "200","message": "success","show_data":[{"productsId":"10025"},{"productsId":"10026"}]}";
    dynamic strItem = ConvertJson(strJson);
    string count = strItem.count.ToString();

    foreach (dynamic item in strItem.show_data)
    {

    HttpContext.Current.Response.Write(item.productsId);
    }


    }
    /// <summary>
    /// Json转化为动态变量
    /// </summary>
    /// <param name="json">json字符段</param>
    /// <param name="isConvertChild">是否转子节点</param>
    /// <returns></returns>
    public static dynamic ConvertJson(string json, bool isConvertChild = true)
    {
    if ((json + "").Length == 0) return new DynamicJsonObject();

    var jss = new JavaScriptSerializer { MaxJsonLength = int.MaxValue };
    jss.RegisterConverters(isConvertChild
    ? new JavaScriptConverter[] { new DynamicJsonConverter() }
    : new JavaScriptConverter[] { new DynamicJsonConverter2() });
    var dy = jss.Deserialize(json, typeof(object)) as dynamic;
    return dy;
    }
    #region DynamicJsonConverter
    //item.productsId
    public class DynamicJsonConverter : JavaScriptConverter
    {
    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
    if (dictionary == null)
    throw new ArgumentNullException("dictionary");

    return type == typeof(object) ? new DynamicJsonObject(dictionary) : null;
    }

    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
    throw new NotImplementedException();
    }

    public override IEnumerable<Type> SupportedTypes
    {
    get { return new ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(object) })); }
    }
    }
    public class DynamicJsonObject : DynamicObject
    {
    private IDictionary<string, object> Dictionary { get; set; }
    public DynamicJsonObject()
    {
    this.Dictionary = new Dictionary<string, object>();
    }
    public DynamicJsonObject(IDictionary<string, object> dictionary)
    {
    this.Dictionary = dictionary;
    }
    /// <summary>
    /// 移除节点
    /// </summary>
    /// <param name="name"></param>
    public void RemoveElement(string name)
    {
    if (Dictionary.ContainsKey(name))
    Dictionary.Remove(name);
    }

    public IDictionary<string, object> GetDictionary()
    {
    return Dictionary;
    }

    public string ToJsonString()
    {
    return GetJson(Dictionary);
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
    if (this.Dictionary.ContainsKey(binder.Name))
    {
    this.Dictionary[binder.Name] = value;
    }
    else
    {
    this.Dictionary.Add(binder.Name, value);
    }
    return true;
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {

    if (this.Dictionary == null || !this.Dictionary.TryGetValue(binder.Name, out result))
    {
    var dictionary = this.Dictionary;
    if (dictionary != null) dictionary.Add(binder.Name, "");
    result = "";
    return true;
    }

    if (result is IDictionary<string, object>)
    {
    result = new DynamicJsonObject(result as IDictionary<string, object>);
    }
    else if (result is ArrayList && (result as ArrayList) is IDictionary<string, object>)
    {
    result =
    new List<DynamicJsonObject>(
    (result as ArrayList).ToArray()
    .Select(x => new DynamicJsonObject(x as IDictionary<string, object>)));
    }
    else if (result is ArrayList)
    {
    result = new List<DynamicJsonObject>(
    (result as ArrayList).ToArray()
    .Select(x => new DynamicJsonObject(x as IDictionary<string, object>)));
    }
    else if (result is int)
    {
    result = result.ToString();
    }

    return this.Dictionary.ContainsKey(binder.Name);
    }
    }
    #endregion

    #region DynamicJsonConverter2
    //item["productsId"]
    public class DynamicJsonConverter2 : JavaScriptConverter
    {
    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
    if (dictionary == null)
    throw new ArgumentNullException("dictionary");

    return type == typeof(object) ? new DynamicJsonObject2(dictionary) : null;
    }

    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
    throw new NotImplementedException();
    }

    public override IEnumerable<Type> SupportedTypes
    {
    get { return new ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(object) })); }
    }
    }
    public class DynamicJsonObject2 : DynamicObject
    {
    private IDictionary<string, object> Dictionary { get; set; }
    public DynamicJsonObject2()
    {
    this.Dictionary = new Dictionary<string, object>();
    }
    public DynamicJsonObject2(IDictionary<string, object> dictionary)
    {
    this.Dictionary = dictionary;
    }
    /// <summary>
    /// 移除节点
    /// </summary>
    /// <param name="name"></param>
    public void RemoveElement(string name)
    {
    if (Dictionary.ContainsKey(name))
    Dictionary.Remove(name);
    }

    public IDictionary<string, object> GetDictionary()
    {
    return Dictionary;
    }

    public string ToJsonString()
    {
    return GetJson(Dictionary);
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
    if (this.Dictionary.ContainsKey(binder.Name))
    {
    this.Dictionary[binder.Name] = value;
    }
    else
    {
    this.Dictionary.Add(binder.Name, value);
    }
    return true;
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {

    if (this.Dictionary == null || !this.Dictionary.TryGetValue(binder.Name, out result))
    {
    var dictionary = this.Dictionary;
    if (dictionary != null) dictionary.Add(binder.Name, "");
    result = "";
    return true;
    }

    if (result is IDictionary<string, object>)
    {
    result = result as IDictionary<string, object>;
    }
    else if (result is ArrayList && (result as ArrayList) is IDictionary<string, object>)
    {
    result =
    new List<IDictionary<string, object>>(
    (result as ArrayList).ToArray()
    .Select(x => x as IDictionary<string, object>));
    }
    else if (result is ArrayList)
    {
    result =
    new List<IDictionary<string, object>>(
    (result as ArrayList).ToArray()
    .Select(x => x as IDictionary<string, object>));
    }
    else if (result is int)
    {
    result = result.ToString();
    }

    return this.Dictionary.ContainsKey(binder.Name);
    }
    }
    #endregion
    public static string GetJson(object obj)
    {
    string str;
    try
    {
    var js = new JavaScriptSerializer { MaxJsonLength = int.MaxValue };
    str = js.Serialize(obj);
    }
    catch
    {
    str = "";
    }
    return str;
    }

    作者:D调灬仔
    出处:https://www.cnblogs.com/chj929555796/
    您的推荐是我最大的动力,如果觉得这篇文章对你有帮助的话,请点个“推荐”哦,博主在此感谢!
  • 相关阅读:
    1058 A+B in Hogwarts (20)
    1036. Boys vs Girls (25)
    1035 Password (20)
    1027 Colors in Mars (20)
    1009. Product of Polynomials (25)
    1006. Sign In and Sign Out
    1005 Spell It Right (20)
    1046 Shortest Distance (20)
    ViewPager页面滑动,滑动到最后一页,再往后滑动则执行一个事件
    IIS7.0上传文件限制的解决方法
  • 原文地址:https://www.cnblogs.com/chj929555796/p/7200038.html
Copyright © 2011-2022 走看看