小编End*_*cvs的帖子

如何使用 DeserializeObject 方法处理空值

我正在使用 Newtonsoft.Json 反序列化对象。我收到以下异常:

Newtonsoft.Json.JsonSerializationException
  HResult=0x80131500
  Message=Error converting value {null} to type 'System.DateTime'. Path 'StartDate', line 1, position 62.
  Source=Newtonsoft.Json
  
Inner Exception 1:
InvalidCastException: Null object cannot be converted to a value type.

Run Code Online (Sandbox Code Playgroud)

原始 json 具有空值:

{
  "StartDate": null,
  "EndDate": null
}
Run Code Online (Sandbox Code Playgroud)

但我向 JsonConvert.DeserializeObject 提供设置以避免空值,如此处此处所述

var convertedMessage = JsonConvert.DeserializeObject<T>(
                Encoding.UTF8.GetString(message.Body),
                new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
Run Code Online (Sandbox Code Playgroud)

知道为什么它一直抛出这个异常吗?

如果提供了实际的日期值,则代码运行良好。

有关代码的更多背景信息,message.Body 是通过服务总线(类 Microsoft.Azure.ServiceBus.Message)接收的消息的正文。对其应用 GetString 方法会返回与发送的消息中相同的字符串。

可运行的代码示例:

using System;
using System.Text;
using Microsoft.Azure.ServiceBus;
using Newtonsoft.Json;


namespace ConsoleApp1
{
    public …
Run Code Online (Sandbox Code Playgroud)

c# json.net azureservicebus

5
推荐指数
1
解决办法
4759
查看次数

标签 统计

azureservicebus ×1

c# ×1

json.net ×1