继承字典的序列化类未序列化属性 [英] Serialize class that inherits dictionary is not serializing properties

查看:108
本文介绍了继承字典的序列化类未序列化属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从Dictionary继承的类,并且有几个属性.当我序列化时,它仅序列化字典而不是属性.如果我有一个包含属性的有效负载,它将对它们反序列化.如何使其对包含属性的对象进行序列化?

I have a class that inherits from Dictionary and has a couple of properties on it. When I serialize it only serializes the dictionary and not the properties. If I have a payload that includes the properties it does deserialize to them. How can I make it serialize my object including the properties?

public class Maintenance : Dictionary<string, dynamic>
{
    public int PersonId { get; set; }
}

return JsonConvert.DeserializeObject<T>(jsonString); //Populates PersonId and all other properties end up in the dictionary.
return JsonConvert.SerializeObject(maintenance); //Only returns dictionary contents

对于如何使序列化使用与反序列化似乎使用的相同行为的建议,我将不胜感激.

I'd appreciate suggestions on how to make serialization use the same behavior as deserialization seems to use.

推荐答案

来自Json.Net文档: 请注意,序列化时仅将字典名称/值写入JSON对象,反序列化时将JSON对象上的属性添加到字典的名称/值..NET字典中的其他成员在序列化过程中将被忽略."

From Json.Net documentation: "Note that only the dictionary name/values will be written to the JSON object when serializing, and properties on the JSON object will be added to the dictionary's name/values when deserializing. Additional members on the .NET dictionary are ignored during serialization."

来自此链接: http://www.newtonsoft.com/json/help/html/SerializationGuide.htm

假设您需要按键&与json输出中PersonId处于同一层次结构级别的字典的值,可以将JsonExtensionData属性与组成而不是继承一起使用,如下所示:

Assuming you want the keys & values of the dictionary on the same hierarchy level as PersonId in the json output, you can use the JsonExtensionData attribute with composition instead of inheritance, like this:

public class Maintenance
{
    public int PersonId { get; set; }

    [JsonExtensionData]
    public Dictionary<string, dynamic> ThisNameWillNotBeInTheJson { get; set; }
}

还要看这个问题:如何序列化字典作为使用Json.Net的父对象的一部分

这篇关于继承字典的序列化类未序列化属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆