首页 > 解决方案 > 比较 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"
   }]
}

标签: c#json

解决方案


一种解决方案是使用Json.NETJson.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);
}

推荐阅读