如何Json.Net没有提供空值和值区分? [英] How to distinguish between null value and value not provided in Json.Net?

查看:200
本文介绍了如何Json.Net没有提供空值和值区分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Json.net反序列化是有办法,我可以在不提供IE丢失关键的空值和值区分?

Using Json.net deserialization is there a way I can distinguish between null value and value that isn't provided i.e. missing key?

我考虑这对使用部分对象更新补丁的请求,他们将代表不同的意图:

I'm considering this for partial object updates using PATCH requests and they would represent different intents:


  • 空 - >设置该属性设置为null

  • 缺失 - >跳过性质未提供

在JavaScript的,这是不确定的和无效的区别

In javascript this is the difference between undefined and null.

我想出了现在最好是使用 JObject

The best I came up with for now is to use JObject.

推荐答案

我有完全相同的问题,我无意中发现在我研究这个问题。

I had the exact same issue and I stumbled on this question during my researches.

这是普遍的共识不满意,我创建扩展可空结构,我把它叫做可设定< T>对于缺乏想象力。基本上它是一个额外的字段为空的,使用isset,这是真的无论哪个值,您存储,只要你存储的东西,只为默认为false(可设定< T>),它的别名是可设定< T&取代。 。未定义

Unsatisfied by the general consensus, I created an extended Nullable struct, which I called Settable<T> for lack of imagination. Basically it is a nullable with an additional field, IsSet, which is true no matter which value you stored, as long as you stored something, and false only for default(Settable<T>), which is aliased as Settable<T>.Undefined.

一个解串器会写的可设置< T>只有当他找到一个相应的属性,在这种情况下使用isset将为真。如果在反序列化JSON是不包括属性,默认将被保留,其具有使用isset ==假。所以,免去您的诠释?在你的DTO类型有可设置的属性是要给你不确定之间所需的差值(或者,更准确地说,未分类)和空。

A deserializer is going to write the Settable<T> only if he finds a corresponding property, in which case IsSet will be true. If the property is not included in the deserialized json, the default will be retained, which has IsSet == false. So, replacing your int? properties in your DTO type with a Settable is going to give you the required difference between undefined (or, more exactly, unspecified) and null.

耶!

我上传的实施到在Github存储库,供大家使用(没有担保,或使用您自己的风险,等等...我在医院,6根肋骨骨折和下止痛药:如果事情不工作这是你的错):

I uploaded the implementation into a repository on Github, for everyone to use (no warranty, use at your own risk, etc... I'm in hospital with 6 broken ribs and under painkillers: if something doesn't work it's YOUR fault):

https://github.com/alberto-chiesa/SettableJsonProperties

编辑:
至于有关未定义序列化的注释为null ,我添加了一个自定义的ContractResolver处理可设置的属性和更新的资料库。

As for the comment about undefined serializing to null, I added a custom ContractResolver to handle Settable properties and updated the repository.

这篇关于如何Json.Net没有提供空值和值区分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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