2

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

CoderGuyy
  • 137
  • 1
  • 7
  • 4
    But `Myclass` has an `id` property so it has to be initialised to something - in this case, its default value of 0. It can't be in an uninitialised state. What would you expect the value of `id` to be? A random number? – Matthew Watson Sep 07 '20 at 13:37

2 Answers2

2

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; }
}
Roman Ryzhiy
  • 1,540
  • 8
  • 5
0

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

Purushothaman
  • 519
  • 4
  • 16