如果我有一个包含值类型属性的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