反序列化对象 DeserializeObject<T> 返回带有空值或默认值的对象。

5

如果我尝试反序列化以下json

{ "error": "Invalid order request" }

当将其反序列化为完全不同结构的类时,我希望会抛出异常。

var response = JsonConvert.DeserializeObject<OrderResponse>(errorJson);

但它返回一个具有默认/空值的对象

response.orderNumber == 0;           // true
response.resultingOrders == null;    // true

以下是我的OrderResponse类:

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;
    }
}

我希望反序列化步骤能够抛出异常或返回空对象。我尝试添加[JsonConstructor]属性来解决这个问题,但结果不理想。
我是做错了什么吗?我需要创建自己的JsonConverter还是可以修改其他的de/serializer设置?

{ "error": "Invalid order request" } 这段 JSON 仅为一个对象。您期望的是什么? - D-Shih
@D-Shih:“我希望反序列化步骤抛出异常或返回一个空对象。” - Camilo Terevinto
1个回答

8
要抛出异常,您需要更改默认的序列化设置。默认情况下,Json.NET会忽略类中缺少的Json成员:

MissingMemberHandling – 默认情况下,此属性设置为Ignore,这意味着如果Json有一个在目标对象中不存在的属性,则会被忽略。将其设置为Error将导致如果Json包含目标对象类型上不存在的成员,则抛出异常。

代码应该像这样:
JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
serializerSettings.MissingMemberHandling = MissingMemberHandling.Error;
var response = JsonConvert.DeserializeObject<OrderResponse>(errorJson, serializerSettings);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接