我有像这样的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。
有任何方法可以使这个属性成为可选项,我希望我的模型没有缺少的属性。
其他想法 当我写这篇文章的时候,我觉得这根本没有任何意义,也许模型是'模型'为什么它在不同的实例中应该是不同的......可能是错的。
任何答案都会被贬低。 感谢
答案 0 :(得分:4)
int
的默认值为0.如果House
是可选的,请将其设为可为空。
[JsonProperty(PropertyName="house")]
public int? House { get; set; }
答案 1 :(得分:1)
将您的媒体资源更改为nullable
类型 - 例如int? House { get; set; }