如何防止在JSON.NET中没有反序列化现有的json属性

时间:2012-07-08 14:55:12

标签: c# json.net deserialization

我有像这样的JSON响应

{
    car:100,
    house:200,
    bike:300
}

但有时某些属性不会出现在响应中。像这样(房子不见了)

{
    car:100,
    bike:300
}

我正在使用JsonConvert.DeserializeObject<Test>(json);

进行反序列化

使用此测试模型

[JsonObject(MemberSerialization.OptIn)]
public class Test
{
    [JsonProperty(PropertyName = "car")]
    public int Car{ get; set; }

    [JsonProperty(PropertyName = "house")]
    public int House{ get; set; }

    [JsonProperty(PropertyName = "bike")]
    public int Bike{ get; set; }
}

现在出现问题: 在第二个例子中,房子丢失了,我仍然得到对象测试,以便将房子设置为0。

有任何方法可以使这个属性成为可选项,我希望我的模型没有缺少的属性。

其他想法 当我写这篇文章的时候,我觉得这根本没有任何意义,也许模型是'模型'为什么它在不同的实例中应该是不同的......可能是错的。

任何答案都会被贬低。 感谢

2 个答案:

答案 0 :(得分:4)

int的默认值为0.如果House是可选的,请将其设为可为空。

[JsonProperty(PropertyName="house")]
public int? House { get; set; }

答案 1 :(得分:1)

将您的媒体资源更改为nullable类型 - 例如int? House { get; set; }