In the event that I try to deserialize the following json
{ "error": "Invalid order request" }
I would expect an exception to be thrown when deserializing it to a class of a completely different structure
var response = JsonConvert.DeserializeObject<OrderResponse>(errorJson);
but instead it returns an object with default/null values
response.orderNumber == 0; // true
response.resultingOrders == null; // true
My OrderResponse class is below:
public class OrderResponse
{
public long orderNumber;
public List<Order> resultingOrders;
[JsonConstructor]
public OrderResponse(long orderNumber, List<Order> resultingOrders)
{
this.orderNumber = orderNumber;
this.resultingOrders = resultingOrders;
}
}
public class Order
{
public long orderId
public decimal amount;
public string type;
[JsonConstructor]
public Order(long orderId, decimal amount, string type)
{
this.orderId = orderId;
this.amount = amount;
this.type; = type;
}
}
I want the deserialization step to throw an exception or return a null object. I thought adding the [JsonConstructor] attributes would resolve the issue, but no dice here.
Am I doing something wrong? Do I need to create my own JsonConverter or can I modify some other de/serializer settings?
To throw an exception, you will have to change the default Serialization Settings. By default, Json.NET ignores when a member of the Json is missing in the class:
MissingMemberHandling
– By default this property is set to Ignore which means that if the Json has a property that doesn’t exist on the target object it just gets ignored. Setting this to Error will cause an exception to be thrown if the json contains members that don’t exist on the target object type.
The code should be something like this:
JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
serializerSettings.MissingMemberHandling = MissingMemberHandling.Error;
var response = JsonConvert.DeserializeObject<OrderResponse>(errorJson, serializerSettings);
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