c# - 比较 JSON 结构
问题描述
我正在测试返回 JSON 的 API。返回的值具有子对象(例如具有 from 和 to 属性的日期对象)。我有一个示例 JSON 字符串和 API 返回的字符串。仅通过键而不是值比较两者的最佳方法是什么,以便仅比较 JSON 的结构(在这种情况下使用 C#,以防有任何裸露)?我见过有人问过类似的问题,但不是我想要的。
目前问题中的 JSON 看起来像这样:
{
"collection":[{
"timePeriod":{
"from": "2017-01-01",
"to": "2017-02-01"
},
"type": "a",
"amount": 463872,
"outstanding": 463872,
"due": "2017-03-08"
}]
}
解决方案
一种解决方案是使用Json.NET和Json.NET Schema nuget 包来根据 JSON 模式验证您的 JSON 字符串。
您可以创建 JSON 架构或基于 C# 对象生成一个。在这种情况下,我生成了一些与您的 JSON 结构匹配的类(对不起类名):
public class RootObject
{
[JsonProperty("collection", Required = Required.Always)]
public List<Item> Collection { get; set; }
public RootObject()
{
Collection = new List<Item>();
}
}
public class Item
{
[JsonProperty("timePeriod", Required = Required.Always)]
public TimePeriod TimePeriod { get; set; }
[JsonProperty("type", Required = Required.Always)]
public string Type { get; set; }
[JsonProperty("amount", Required = Required.Always)]
public int Amount { get; set; }
[JsonProperty("outstanding", Required = Required.Always)]
public int Outstanding { get; set; }
[DataType(DataType.Date)]
[JsonProperty("due", Required = Required.Always)]
public DateTime Due { get; set; }
}
public class TimePeriod
{
[DataType(DataType.Date)]
[JsonProperty("from", Required = Required.Always)]
public DateTime From { get; set; }
[DataType(DataType.Date)]
[JsonProperty("to", Required = Required.Always)]
public DateTime To { get; set; }
}
我假设所有属性都是必需的。此外,关于 DateTime 属性,我使用数据注释来指定日期不包含时间部分(而不是完整的 ISO 日期)。
验证架构:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Schema.Generation;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string json = @"{
""collection"":[{
""timePeriod"":{
""from"": ""2017-01-01"",
""to"": ""2017-02-01""
},
""type"": ""a"",
""amount"": 463872,
""outstanding"": 463872,
""due"": ""2017-03-08""
}]
}";
var generator = new JSchemaGenerator();
JSchema schema = generator.Generate(typeof(RootObject));
JObject data = JObject.Parse(json);
bool isValidSchema = data.IsValid(schema);
}
}
}
您还可以获得如下架构错误:
IList<string> messages;
bool isValidSchema = data.IsValid(schema, out messages);
foreach (string message in messages)
{
Console.WriteLine(message);
}
推荐阅读
- flutter - Flutter - 在套接字连接中的有状态小部件之间传递数据
- python - 如何将类的方法返回的值作为PyTest中测试用例的参数传递?
- graphql - Apollo 客户端 - 在终止链接上调用 concat,这将不起作用
- swift - 从firebase获取数据而不调用自己的数据
- c# - .NET foreach 循环问题,以便将结果导出到 Excel 文件
- python - 如何将异常与 pybind11 中的自定义字段和构造函数绑定,并且仍然让它们作为 python 异常起作用?
- javascript - 导航上出现空白 - SafeView
- jquery - 我的 jquery 代码在承诺方面有什么问题
- python - 获取原始 sys.argv
- python - Keras:生成器在开始第二个时期时用完了数据