【问题标题】:null value exception thrown when deserializing null value JSON.net反序列化空值 JSON.net 时抛出空值异常
【发布时间】:2010-06-07 10:35:55
【问题描述】:

嗨朋友我正在尝试将隐藏的控制字段反序列化为 JSON 对象,代码如下:

Dim settings As New Newtonsoft.Json.JsonSerializerSettings() 
settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore
Return Newtonsoft.Json.JsonConvert.DeserializeObject(Of testContract)(txtHidden.Text, settings) 

但我收到以下异常。 value cannot be null parameter name s: 我什至添加了以下几行,但仍然无法正常工作。请帮忙。

settings.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore
settings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore 
settings.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace 

【问题讨论】:

  • 除非你混淆了你的标题,否则答案是显而易见的,你给你的代码一个空值,这就是抛出 NullValueException 的原因
  • 我之前使用的版本中没有抛出。我正在使用 JSON.net 3.5
  • 这到底是怎么回事?你知道错误是在哪里引发的吗? (这个“s”参数是什么?它与您尝试反序列化的对象有关,还是与Json.Net有关?)

标签: .net json json.net


【解决方案1】:

当我尝试调用相同的方法时,我得到了完全相同的错误消息。确保您的目标类(您的testContract 类)有一个默认构造函数(没有参数的构造函数)。

在 C# 中,您的类和默认构造函数如下所示:

class testContract
{
    string StringProperty;
    int IntegerProperty;

    public testContract()
    {
        // This is your default constructor. Make sure this exists.
        // Do nothing here, or set default values for your properties
        IntegerProperty = -1;
    }

    public testContract(string StringProperty, int IntegerProperty)
    {
        // You can have another constructor that accepts parameters too.
        this.StringProperty = StringProperty;
        this.IntegerProperty = IntegerProperty;
    }
}

当 JSON.net 想要将 JSON 字符串反序列化为对象时,它首先使用其默认构造函数初始化该对象,然后开始填充其属性。如果它没有找到默认构造函数,它将使用它可以找到的任何其他构造函数来初始化对象,但它会将null 传递给所有参数。

简而言之,您应该为您的 目标类,或者,您的非默认构造函数必须能够处理 所有空参数。

【讨论】:

  • 我在使用 Ninject 和 SignalR 时遇到了这个错误 - 允许一个空的构造函数并设置 int i = -1;为我修好了。
  • 如果你使用 [Serializable] 你应该已经有你的默认 ctor 否则它不能成为数据绑定的一部分。结帐 [JsonPropertyAttribute("jsonProp", Required=Required.Default)] 适合我
【解决方案2】:

如果您使用 [Serializable],您应该已经拥有默认 ctor,否则它不能成为数据绑定的一部分。结帐

  [JsonPropertyAttribute("jsonProp", Required=Required.Default)] 

该物业对我有用

Newtonsoft 有方法

Parse - 将解析部分数据 和 反序列化 - 将解析整个数据

如果您希望使用部分数据,例如他们网站上的示例,请使用 Parse。

如果你想使用反序列化,你需要确保你的所有属性都存在,并且像我上面写的那样用 Default 标记。

【讨论】:

    猜你喜欢
    • 2013-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多