使用Schema验证无效的json数据不会因反序列化而失败

时间:2019-11-15 07:06:56

标签: c# asp.net-web-api json.net json-deserialization

我正在解析以下JSON:

{"names":{"organizationNames":[{"name":"apple"}]}} 

进入C#代码中定义的架构,如下所示。

public class QueryJson
{

    #region Properties

    [JsonProperty("organization")]
    public HeOrganization Organization { get; set; }

    [JsonProperty("names")]
    public HeName Names { get; set; }

    [JsonProperty("emails")]
    public List<HeEmailAddress> Emails { get; set; }

    #endregion


    #region Linked Classes

    public class HeOrganization
    {
        [JsonProperty("id")]
        public Guid? ID { get; set; }
    }

    public class HeName
    {
        [JsonProperty("organizationNames")]
        [Required(ErrorMessage = "Organization Name is Missing")]
        public List<HeOrganizationName> OrganizationName { get; set; }

        public class HeOrganizationName
        {
            [JsonProperty("name")]
            [Required(ErrorMessage = "Name is Missing")]
            public string Name { get; set; }
        }
    }

    public class HeEmailAddress
    {
        [JsonProperty("address")]
        [Required]
        [EmailAddress]
        public string Address { get; set; }

    }

    #endregion

}

如果我要传递明显无效的JSON:

{"names":{"organizationNames":[{"user":"apple"}]}}

我期望DeserializeObject()失败或抛出错误,但是它只是将'Name'分配为null。

var myJson = JsonConvert.DeserializeObject<T>(jsonFilter);

其中T是类的实例。

关于如何执行此类验证的任何建议?

1 个答案:

答案 0 :(得分:0)

您可以使用Newtonsoft.Json.Schema来验证任何给定Json的架构。

例如,对于您定义的类结构,可以将等效模式生成为

var generator = new JSchemaGenerator();
var schema = generator.Generate(typeof(QueryJson));

生成的架构如下

{
  "definitions": {
    "HeEmailAddress": {
      "type": [
        "object",
        "null"
      ],
      "properties": {
        "address": {
          "type": "string",
          "format": "email"
        }
      },
      "required": [
        "address"
      ]
    },
    "HeName": {
      "type": [
        "object",
        "null"
      ],
      "properties": {
        "organizationNames": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/HeOrganizationName"
          }
        }
      },
      "required": [
        "organizationNames"
      ]
    },
    "HeOrganization": {
      "type": [
        "object",
        "null"
      ],
      "properties": {
        "id": {
          "type": [
            "string",
            "null"
          ]
        }
      },
      "required": [
        "id"
      ]
    },
    "HeOrganizationName": {
      "type": [
        "object",
        "null"
      ],
      "properties": {
        "name": {
          "type": "string"
        }
      },
      "required": [
        "name"
      ]
    }
  },
  "type": "object",
  "properties": {
    "organization": {
      "$ref": "#/definitions/HeOrganization"
    },
    "names": {
      "$ref": "#/definitions/HeName"
    },
    "emails": {
      "type": [
        "array",
        "null"
      ],
      "items": {
        "$ref": "#/definitions/HeEmailAddress"
      }
    }
  },
  "required": [
    "organization",
    "names",
    "emails"
  ]
}

您现在可以使用Schema来验证json。例如,对于OP中提供的示例无效json

var invalidJson = @"{""names"":{""organizationNames"":[{""user"":""apple""}]}}";
var jsonInstance = JObject.Parse(invalidJson);
bool valid = jsonInstance.IsValid(schema); // False