从动态对象获取属性值

时间:2019-03-27 11:54:44

标签: c# json dynamic

我试图通过指定属性名称来从动态对象获取属性值,它使用索引工作,但是我需要传递一个特定的属性名称来获取值(因为名称将存储在Db中,而不是存储在Db中。索引]

var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new DynamicJsonConverter() });

dynamic data = serializer.Deserialize(jsonText, typeof(object));
data.Response.Outcome.KeyValueOfstringOutcomepQnxSKQu["PropertyName"]

这是将我的jSON转换为动态类的代码,我正尝试从该动态类中获取指定属性的值

public sealed 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[] { typeof(object) })); }
    }

    #region Nested type: DynamicJsonObject

    private sealed class DynamicJsonObject : DynamicObject
    {
        private readonly IDictionary<string, object> _dictionary;

        public DynamicJsonObject(IDictionary<string, object> dictionary)
        {
            if (dictionary == null)
                throw new ArgumentNullException("dictionary");
            _dictionary = dictionary;
        }

        public override string ToString()
        {
            var sb = new StringBuilder("{");
            ToString(sb);
            return sb.ToString();
        }

        private void ToString(StringBuilder sb)
        {
            var firstInDictionary = true;
            foreach (var pair in _dictionary)
            {
                if (!firstInDictionary)
                    sb.Append(",");
                firstInDictionary = false;
                var value = pair.Value;
                var name = pair.Key;
                if (value is string)
                {
                    sb.AppendFormat("{0}:\"{1}\"", name, value);
                }
                else if (value is IDictionary<string, object>)
                {
                    new DynamicJsonObject((IDictionary<string, object>)value).ToString(sb);
                }
                else if (value is ArrayList)
                {
                    sb.Append(name + ":[");
                    var firstInArray = true;
                    foreach (var arrayValue in (ArrayList)value)
                    {
                        if (!firstInArray)
                            sb.Append(",");
                        firstInArray = false;
                        if (arrayValue is IDictionary<string, object>)
                            new DynamicJsonObject((IDictionary<string, object>)arrayValue).ToString(sb);
                        else if (arrayValue is string)
                            sb.AppendFormat("\"{0}\"", arrayValue);
                        else
                            sb.AppendFormat("{0}", arrayValue);

                    }
                    sb.Append("]");
                }
                else
                {
                    sb.AppendFormat("{0}:{1}", name, value);
                }
            }
            sb.Append("}");
        }

        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;
        }

        public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
        {
            if (indexes.Length == 1 && indexes[0] != null)
            {
                if (!_dictionary.TryGetValue(indexes[0].ToString(), out result))
                {
                    // return null to avoid exception.  caller can check for null this way...
                    result = null;
                    return true;
                }

                result = WrapResultObject(result);
                return true;
            }

            return base.TryGetIndex(binder, indexes, out result);
        }

        private static object WrapResultObject(object result)
        {
            var dictionary = result as IDictionary<string, object>;
            if (dictionary != null)
                return new DynamicJsonObject(dictionary);

            var arrayList = result as ArrayList;
            if (arrayList != null && arrayList.Count > 0)
            {
                return arrayList[0] is IDictionary<string, object>
                    ? new List<object>(arrayList.Cast<IDictionary<string, object>>().Select(x => new DynamicJsonObject(x)))
                    : new List<object>(arrayList.Cast<object>());
            }

            return result;
        }
    }

    #endregion
}

这是杰森

{
    "Response": {
        "Outcome": {
            "KeyValueOfstringOutcomepQnxSKQu": [{
                "Key": "Icon",
                "Value": {
                    "DataType": "System.String",
                    "Field": "Icon",
                    "Value": "O"
                }
            }, {
                "Key": "IconDescription",
                "Value": {
                    "DataType": "System.String",
                    "Field": "IconDescription",
                    "Value": "Old"
                }
            }, {
                "Key": "IconLongDescription",
                "Value": {
                    "DataType": "System.String",
                    "Field": "IconLongDescription",
                    "Value": "Older"
                }
            }]
        }
    }
}

期望得到

dynamic data = serializer.Deserialize(jsonText, typeof(object));
data.Response.Outcome.KeyValueOfstringOutcomepQnxSKQu["Icon"].Field.Value

O的期望值

1 个答案:

答案 0 :(得分:1)

这是使用Json.NET的一种解决方案:

dynamic data = JsonConvert.DeserializeObject(jsonText, typeof(object));
var list = data.Response.Outcome.KeyValueOfstringOutcomepQnxSKQu as IEnumerable<dynamic>;
var iconNode = list.FirstOrDefault(r => r.Key == "Icon");
var valueOfO = iconNode.Value.Value.Value;

编辑:替代解决方案:由于您的数据似乎是结构化的,并且您正在从json读取硬编码的路径,因此,我希望您创建模型类而不是使用动态对象。以下是一个工作模型类的示例,您可以使用JsonConvert.DeserializeObject<Rootobject>(jsonText)

反序列化
public class Rootobject
{
    public Response Response { get; set; }
}

public class Response
{
    public Outcome Outcome { get; set; }
}

public class Outcome
{
    public Keyvalueofstringoutcomepqnxskqu[] KeyValueOfstringOutcomepQnxSKQu { get; set; }
}

public class Keyvalueofstringoutcomepqnxskqu
{
    public string Key { get; set; }
    public Value Value { get; set; }
}

public class Value
{
    public string DataType { get; set; }
    public string Field { get; set; }
    [JsonProperty("Value")]
    public string Value1 { get; set; }
}