CoderGuyy
CoderGuyy

Reputation: 147

How to prevent initialization of properties which are not present in JSON string during Deserialization in C#?

My given class is :

public class Myclass
    {
        public int id { get; set; }

        public string name{ get; set; }
    }

I am passing jsonString like this:

var jsonString = @"{ 'name': 'John'}".Replace("'", "\"");

When i try to deserialize above json string using following code :

var visitData = JsonConvert.DeserializeObject<Myclass>(jsonString, jsonSerialize);

I am getting following values in visitData :

id : 0
name : "john"

But i want to ignore the id property as it is not present in jsonString.

How should i implement this functionality in Console Application of .Net Core 3.1 in C#.

Upvotes: 2

Views: 759

Answers (2)

Purushothaman
Purushothaman

Reputation: 579

Usually deserializer will look for the matching property from the json string, if not exist then the default value is assigned. In your case the default value of int is 0. Again if you make the int as nullable int then again the default value will be assigned i.e., null.

For Newtonsoft.Josn create a contract resolver and manage your serialization/deserialization. Please find the detail information here Should not deserialize a property

Upvotes: 0

Roman Ryzhiy
Roman Ryzhiy

Reputation: 1646

You can try to declare id as a nullable property

public class Myclass
{
    public int? id { get; set; } // a nullable property

    public string name{ get; set; }
}

Upvotes: 2

Related Questions