gpt4 book ai didi

C# - 检查 JSON 结构是否更改

转载 作者:行者123 更新时间:2023-11-30 20:27:17 25 4
gpt4 key购买 nike

我正在使用 Newstonsoft.JSON 来处理从 Internet 获取的 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

}

最佳答案

您可以创建 JSON 架构并使用 JSON.Net 根据该架构验证 JSON 文件,如下所示:

JsonSchema schema = JsonSchema.Parse(jsonSchema);
JObject obj = JObject.Parse(jsonString);
bool valid = obj.IsValid(schema);

更多信息可以找到herehere .

或者,如果您只想检查收到的 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
});

关于C# - 检查 JSON 结构是否更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48793131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com