验证远程JSON,而不是解析它

本文关键字:JSON 验证 | 更新日期: 2023-09-27 18:04:04

我使用的是NewtonSoft。Json解析器用于解析远程URL。

我的远程JSON示例如下

Kerberos.load({"todays" : "Fri, Mar 15",
    "datas" : [
            {
                "id" : "2021200303"
            }
            ]});

我正在解析JSON示例如下

using (var WebClient = new System.Net.WebClient())
{
    WebClient.Encoding = System.Text.Encoding.UTF8;
    var _Json = WebClient.DownloadString(_MyJsonRemoteURL_);
    _Json = _Json.Replace("Kerberos.load(", "");
    _Json = _Json.Replace("]});", "]}");
    dynamic _Dynamic = JsonConvert.DeserializeObject(_Json);
    foreach (var _JsonNode in _Dynamic.datas)
    {
        MessageBox.Show(_JsonNode.SelectToken("id").ToString());
    }
}

所以,有没有任何方法来验证远程JSON字符串,而不使用替换方法?

验证远程JSON,而不是解析它

如果你想为JSON做这件事,这是非常可能的,看看合同测试JSON服务在。net

交叉张贴的代码在这里快速参考,更详细的检查链接

[Test]
public void ShouldBeAbleToValidateTheJSONServiceResponseForFunctionalityA()
{
    const string schemaJson = @"
{
    'description': 'Service Response',
    'type': 'object',
    'properties': {
        'product': {
            'type': 'object',
            'properties': {
                'availability': {
                        'type': 'array',
                        'items': {
                                    'type': 'object',
                                    'properties': {
                                                    'Local': { 'type' : 'number'},
                                                    'Storehouse': { 'type' : 'number'},
                                                } 
                                }
                    }
            }        
        }
    }
}";
    var parameters = new Dictionary<string, object> { { "id", 1 }, { "city", "Chennai" } };
    AssertResponseIsValidSchema(schemaJson, parameters);
}