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

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

问题描述

我在 .NET 4.5 windows 商店应用程序中使用股票 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 序列化,因为数据成员 'Date' 在其类型层次结构中是重复的.

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天全站免登陆