分享

如何在JsonConvert.DeserializeObject中处理null / empty值

 行走在理想边缘 2020-07-27

I have the following code:

return (DataTable)JsonConvert.DeserializeObject(_data, (typeof(DataTable)));

Then, I tried:

var jsonSettings = new JsonSerializerSettings
{
    NullValueHandling = NullValueHandling.Ignore
};

return (DataTable)JsonConvert.DeserializeObject<DataTable>(_data, jsonSettings);

The return line is throwing the error:

{"Error converting value \"\" to type 'System.Double'."}

Lots of solutions online suggesting creating custom Class with nullable types but this won't work for me. I can't expect the json to be in a certain format. I have no control over the column count, column type, or column names.

解决方案

You can supply settings to JsonConvert.DeserializeObject to tell it how to handle null values, in this case, and much more:

var settings = new JsonSerializerSettings
                    {
                        NullValueHandling = NullValueHandling.Ignore,
                        MissingMemberHandling = MissingMemberHandling.Ignore
                    };
var jsonModel = JsonConvert.DeserializeObject<Customer>(jsonString, settings);

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约