将名称/值对反序列化为对象

时间:2017-05-27 01:17:23

标签: c# json json.net

我有一组名称/值对,用名称和值定义它们就像一个键/值对象,即

[{"Name":"ActivityId","DataType":1,"Value":"a7868f8c-07ac-488d-a414-714527c2e76f"}, 
 {"Name":"Address1","DataType":2,"Value":"123 Main St"}]

如果我有一个像这样的对象:

class Request
{
    public Guid ActivityId { get; set; }
    public string Address1 {get; set; }
}

如何将其反序列化到上面的类?

我应该考虑自定义转换器吗? Json.NET有内置的东西吗?有没有办法用我缺少的属性来装饰属性?定制序列化会更容易吗?

我试图避免从Dictionary中提取每个属性的数据,这将是简单的路径,但需要我对每个自定义实现执行此操作。我更喜欢在使用Json.NET(或.NET框架中的某些东西)的单个方法中在基类中执行此操作。

我搜索了很多,大多数示例都是实名/值对,没有名称和值的前缀,即

[{"ActivityId":"a7868f8c-07ac-488d-a414-714527c2e76f"}]

有什么想法吗?

1 个答案:

答案 0 :(得分:4)

这可以通过下面的自定义JsonConverter以简单的方式完成。转换器首先将名称 - 值对数组转换为JObject,其属性镜像对,然后使用序列化程序的内置JObject方法从Populate填充目标对象

class NameValueConverter : JsonConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // Load the array of name-value pairs and transform into a JObject.
        // We are assuming all the names will be distinct.
        JObject obj = new JObject(
            JArray.Load(reader)
                  .Children<JObject>()
                  .Select(jo => new JProperty((string)jo["Name"], jo["Value"]))
        );

        // Instantiate the target object and populate it from the JObject.
        object result = Activator.CreateInstance(objectType);
        serializer.Populate(obj.CreateReader(), result);
        return result;
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        // WriteJson is not called when CanWrite returns false
        throw new NotImplementedException();
    }

    public override bool CanConvert(Type objectType)
    {
        // We only want this converter to handle classes that are expressly
        // marked with a [JsonConverter] attribute, so return false here.
        // (CanConvert is not called when [JsonConverter] attribute is used.)
        return false;
    }
}

要使用转换器,只需向目标类添加[JsonConverter]属性:

[JsonConverter(typeof(NameValueConverter))]   
class Request
{
    public Guid ActivityId { get; set; }
    public string Address1 {get; set; }
}

然后,您可以像往常一样反序列化:

Request req = JsonConvert.DeserializeObject<Request>(json);

小提琴:https://dotnetfiddle.net/tAp1Py