Search code examples
c#jsonasp.net-core.net-corejson-deserialization

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#.


Solution

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