Customize Json.NET serialization to consider empty

2019-09-07 05:01发布

问题:

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

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.

So if I have a variable in JavaScript

icon_id : null

When I get the JObject server-side it becomes

icon_id : ""

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.

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 ?

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.

回答1:

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