我使用Newstonsoft.JSON处理我从互联网上获得的JSON文件,但文件经常会改变结构,我不想每天检查它是否没有改变。如何检查结构是否已更改?我不关心数组中的值或元素数量(但我关心孩子的结构)。我怎样才能做到这一点?
{
"abc": true, // I want to check if there is "abc", but I don't care if it is true or false
"def": 4, // I want to check if there is "def", but I don't care which value it has
[
{
"ghi": false // I want to check if all the children has ghi,but I don't check the value
}
] // I don't care if there is 1 or 1000 elements in array
}
答案 0 :(得分:4)
您可以使用 JSON.Net 创建JSON模式并根据该模式验证JSON文件,类似:
JsonSchema schema = JsonSchema.Parse(jsonSchema);
JObject obj = JObject.Parse(jsonString);
bool valid = obj.IsValid(schema);
或者,如果您只想检查您收到的JSON是否具有相应DTO类的所有属性,则可以使用[JsonProperty(Required = Required.Always)]
属性标记所有属性:
class Person
{
[JsonProperty(Required = Required.Always)]
public string Name { get; set; }
[JsonProperty(Required = Required.Always)]
public int Age { get; set; }
}
如果你想检测JSON与DTO相比是否有一些额外的属性,你可以这样做:
JsonConvert.DeserializeObject<Person>(jsonString, new JsonSerializerSettings
{
MissingMemberHandling = MissingMemberHandling.Error
});