2010-06-07 66 views
2

喜的朋友,当我试图反序列化一个隐藏的控制领域成JSON对象的代码如下抛出:空值异常反序列化空值JSON.net

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 
+0

除非您混淆了标题,否则答案显而易见,您将为您的代码赋予一个空值,这就是为什么抛出NullValueException的原因。 – Woot4Moo 2010-06-07 10:42:33

+0

在我以前使用的版本中没有抛出它。我正在使用JSON.net 3.5 – Bharath 2010-06-08 03:48:00

+0

到底发生了什么?你知道错误提出的地方吗? (什么是这个“s”参数?是否与你试图反序列化的对象有关,或者与Json.Net有关?) – Tao 2010-06-20 16:49:51

回答

7

我有同样的确切的错误信息,因为我试着调用相同的方法。确保你的目标类(你的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传递给所有参数。

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

+0

我使用Ninject和SignalR得到这个错误 - 允许一个空的构造函数和设置int i = -1;为我修好了。 – boolean 2012-03-17 20:21:00

+0

如果你使用[Serializable],你已经应该有你的默认ctor,否则它不能成为数据绑定的一部分。结帐[JsonPropertyAttribute(“jsonProp”,Required = Required.Default)]适用于我 – 2012-05-08 17:40:21

0

如果你使用[Serializable]你已经应该有你的默认ctor,否则它不能成为数据绑定的一部分。对房地产结账

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

对我的作品

Newtonsoft有方法

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

,如果你想使用部分数据(如他们网站上的示例)使用Parse。

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