null value exception thrown when deserializing null value JSON.net

早过忘川 提交于 2019-12-10 11:13:17

问题


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 

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/2988724/null-value-exception-thrown-when-deserializing-null-value-json-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!