gpt4 book ai didi

c# - DeserializeObject 返回具有空/默认值的对象

转载 作者:行者123 更新时间:2023-12-04 00:30:52 26 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Detect if deserialized object is missing a field with the JsonConvert class in Json.NET

(5 个回答)


3年前关闭。




如果我尝试反序列化以下 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 还是可以修改其他一些反序列化器设置?

最佳答案

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

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.



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

关于c# - DeserializeObject<T> 返回具有空/默认值的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51343740/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com