C# – JSON.Net Ignore Property during deserialization

cjsonjson.net

I have a class set up as follows:

public class Foo
{
    public string string1 { get; set; }
    public string string2 { get; set; }
    public string string3 { get; set; }
}

I am using Json.Net to deserialize the following Json Response:

[
    {
        "number1": 1,
        "number2": 12345678901234567890,
        "number3": 3
    },
    {
        "number1": 9,
        "number2": 12345678901234567890,
        "number3": 8
    }
]

Deserialization code:

string json = @"[
    {
        ""number1"": 1,
        ""number2"": 12345678901234567890,
        ""number3"": 3
    },
    {
        ""number1"": 9,
        ""number2"": 12345678901234567890,
        ""number3"": 8
    }
]"

List<Foo> foos = JsonConvert.DeserializeObject<List<Foo>>(json);

The value in number2 exceeds an Int64, but I don't really care about retrieving that value. Is there a way to cast the number2 property to a string, or fully ignore it during deserialization?

I have tried adding the [JsonConverter(typeof(string))] attribute to the string2 property, but recieve the error: Error creating System.String. I have also tried setting typeof(decimal).

I have also tried using [JsonIgnore] but that doesn't work.

Best Answer

You can use MissingMemberHandling property of the JsonSerializerSettings object.

Example usage:

var jsonSerializerSettings = new JsonSerializerSettings();
jsonSerializerSettings.MissingMemberHandling = MissingMemberHandling.Ignore;

JsonConvert.DeserializeObject<YourClass>(jsonResponse, jsonSerializerSettings);

More info here.