Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DeserializeObject<T> returns object with null/default values [duplicate]

Tags:

c#

json.net

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?

like image 952
Justin Avatar asked Jul 14 '18 22:07

Justin


1 Answers

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);
like image 107
Nathalia Soragge Avatar answered Nov 09 '22 15:11

Nathalia Soragge