开发者

null value exception thrown when deserializing null value JSON.net

Hi Friends I am trying to deserialize a hidden control field into a JSON object the code is as follows开发者_运维知识库:

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

But I am getting the following exception. value cannot be null parameter name s: I even added the following lines but it still does not work out. Please help.

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


I had the same exact error message as I tried calling the same method. Make sure you have a default constructor (constructor with no parameters) for your target class (your testContract class).

In C# your class and default constructor would look something like this:

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;
    }
}

When JSON.net wants to deserialize a JSON string into an object, it first initializes the object using its default constructor and then starts populating its properties. If it doesn't find a default constructor, it will initialize the object using whatever other constructor that it can find, but it will pass null to all parameters.

In a nutshell, You should either have a default constructor for your target class, or, your non-default constructor must be able to handle all null parameters.


if you use [Serializable] you already should have your default ctor otherwise it can't be part of data binding. checkout

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

on the property works for me

Newtonsoft has to methods

Parse - will parse partial data and Deserialize - will parse entire data

if you wish to use partial data, like in the example on their website, use Parse.

If you wish to use Deserialize you need to make sure all your properties exist and are marked with Default like i wrote above.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜