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.
To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.
If you only care about deserialization, another simple thing you could do is to define the enum field as string and add another 'get' only field that parses the string field to either one of the known values or to 'unknown'. This field should be 'JsonIgnore'd.
DeserializeObject(String, Type,JsonConverter[]) Deserializes the JSON to the specified . NET type using a collection of JsonConverter. DeserializeObject(String, Type, JsonSerializerSettings) Deserializes the JSON to the specified .
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.
This is a lame workaround but you could make a method to manually load the json. If it's too much data to load without an automatic deserializer just remove the nodes that you don't want. This is a lot slower though.
public static List<Foo> FromJson(string input) { var json = JToken.Parse(input); json["key"].Remove(); var foo = JsonConvert.DeserializeObject<List<Foo>>(json.ToString()); }
This is an interesting problem I wonder if anyone has a better solution for it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With