2010-06-07 25 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,就像我上面寫的那樣。