仅当JSON为值类型属性指定值时,才反序列化JSON



如果我有一个包含值类型属性的DTO类,如何在确保JSON定义值类型(可能包含该类型的default值(的同时,惯用地使用Newtonsoft将JSON反序列化为DTO类?到目前为止,我看到的方法都依赖于检查该值是否为default值,但是,当default值也是该属性的有效值时,这不是一个合适的解决方案。

示例

public class MyDto
{
public bool MyProp { get; set; }
}
JSON可以反序列化为MyDto
{"MyProp": true}
{"MyProp": false}
{}错误

我相信您想要的是JsonPropertyAttribute Required属性:

public class MyDto
{
[JsonProperty(Required = Required.Always)]
public bool MyProp { get; set; }
}

当反序列化的JSON不包含指定的属性(MyProp(时,会导致异常。例如,以下内容:

string json = "{"MyProp": true}";
MyDto myDto = JsonConvert.DeserializeObject<MyDto>(json);
Console.WriteLine(myDto.MyProp);
json = "{"MyProp": false}";
myDto = JsonConvert.DeserializeObject<MyDto>(json);
Console.WriteLine(myDto.MyProp);
json = "{}";
myDto = JsonConvert.DeserializeObject<MyDto>(json);
Console.WriteLine(myDto.MyProp);

给出结果:

True
False
Run-time exception (line 17): Required property 'MyProp' not found in JSON. Path '', line 1, position 2.

您可以使用JSON模式(Newtonsoft.JSON.Schema(验证JSON,如下所示:

public class MyDto
{
[JsonProperty(Required = Required.Always)]
public bool MyProp { get; set; }
}

var generator = new JSchemaGenerator();
var schema = generator.Generate(typeof(MyDto));
var dto = JObject.Parse(@"{ 'MyProp': true }");
bool isValid = dto.IsValid(schema);
Console.WriteLine(isValid); // True
dto = JObject.Parse(@"{}");
isValid = dto.IsValid(schema);
Console.WriteLine(isValid); // False

最新更新