2

嗨朋友我正在尝试将隐藏的控制字段反序列化为 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 
4

2 回答 2

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给所有参数。

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

于 2010-08-12T01:11:07.437 回答
0

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

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

在物业上为我工作

Newtonsoft 有方法

Parse - 将解析部分数据和 Deserialize - 将解析整个数据

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

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

于 2012-05-08T17:43:11.407 回答