自定义Json.NET序列化以将空字符串视为null [英] Customize Json.NET serialization to consider empty strings as null

查看:189
本文介绍了自定义Json.NET序列化以将空字符串视为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有一个愚蠢的问题.我正在使用ASP .NET MVC 4,EF5和Ext JS(Sencha)开发Web应用程序.

I have a stupid problem here. I'm developing a web application with ASP .NET MVC 4, EF5, and Ext JS (Sencha).

问题是,根据设计(我不知道为什么),Ext JS在执行ajax请求时会将具有空值的js对象转换为空字符串.

The thing is, by design (I don't know why), Ext JS when doing ajax requests is converting js objects with null values to empty strings.

仅出于此目的,我将简化该示例.

I'll over simplify the example just for the sake of it.

所以,如果我在JavaScript中有一个变量

So if I have a variable in JavaScript

icon_id : null

当我获得JObject服务器端时,它变成

When I get the JObject server-side it becomes

icon_id : ""

当我通过icon_id作为请求的参数时.因此,当我写icon_id.ToObject<MyNETIconIDClass>()时,我得到一个异常,告诉我它不能从字符串转换为可为null的int.这是可以理解的.

when I pass icon_id as the parameter for the request. So when I write icon_id.ToObject<MyNETIconIDClass>() I get an exception which tells me it can't convert from string to nullable int. Which is understandable.

我可能会误解其背后的逻辑,但是由于我不想弄乱Ext JS源代码,所以有什么办法可以告诉Json.NET反序列化器将空字符串视为null?

I may be misunderstanding the logic behind this, but since I don't want to mess around with Ext JS source code, is there any way I could tell the Json.NET deserializer to consider empty strings as null ?

据我所知,使用转换器会很麻烦,因为我必须更改模型中每个类中的每个可为null的int属性,以使其正常工作.

And as far as I've seen, using converters would be troublesome because I would have to change every nullable int property in every class in my model just to make this work right.

推荐答案

根据注释,OP发送的是GET请求,而不是POST.

As per comments, OP was sending a GET request as opposed to a POST.

这篇关于自定义Json.NET序列化以将空字符串视为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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