为什么JSON序列化器不符合多态性? [英] Why json serializer is not compliant with polymorphism?

查看:113
本文介绍了为什么JSON序列化器不符合多态性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在.NET 4.5 Windows Store应用程序中使用库存JSON序列化程序-

I use stock JSON serialiser in .NET 4.5 windows store app -

System.Runtime.Serialization.Json.DataContractJsonSerializer

我有一个由API提供程序提供的类

I have a class which is supplied by the API provider say

class A { public DateTime Date {get;set} }

我想通过执行以下操作来隐藏日期"字段(注意- new 关键字):

I wanted to hide Date field by doing this (NOTE - new keyword):

class AEx : A { public new string Date {get;set} }  

但是我遇到了异常:

类型'AEx'不能通过DataContractJsonSerializer进行序列化,因为数据成员'日期'在其类型层次结构中是重复的.

type 'AEx' is not serializable with DataContractJsonSerializer because the data member 'Date' is duplicated in its type hierarchy.

我了解它的作用.但是,我的问题是如何,它为什么但是为什么?

I understand what it does.. My question however is not HOW does it do but why?

从逻辑上讲,它应该与多态性等编程功能兼容. 为什么要让此类忽略它?

Logically speaking it should be compatible with the programming features like polymorphism. Why this class was made to ignore it?

推荐答案

您的类基本上包含两个具有相同名称的属性.因此,如果您尝试反序列化一些包含该属性名称的JSON,则无法知道要设置哪个属性.

Your class basically contains two properties with the same name. So if you try to deserialize some JSON which contains that property name, there's no way of knowing which property to set.

类似地,当序列化该类型的对象时,您需要使用相同的属性名称对两个值进行序列化-您将JSON期望 使用什么看起来像什么?

Likewise when serializing an object of that type, you've got two values which need to be serialized using the same property name - what would you expect the JSON to look like?

从根本上讲,具有两个相同名称的属性的类型与纯名称/值对格式的序列化不兼容. (一种更高级的序列化机制,可以指定与哪个声明类关联的属性,而JSON则不行.)

Fundamentally, a type with two properties of the same name is incompatible with serialization of a plain name/value pair format. (A more advanced serialization mechanism which could specify which property was associated with which declaring class would cope, but JSON doesn't do that.)

这篇关于为什么JSON序列化器不符合多态性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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