首页 > 解决方案 > 如何验证 json 是类对象的正确表示?

问题描述

我收到了一些应该代表某个类的合法对象的 json。我希望验证确实如此。所以我反序列化了字符串,看看是否成功。这非常耗时,因为在某些情况下字符串会变得非常大并且其中有很多。因此,我正在寻找一种不同的方法。

我想从类的定义中创建一个 regExp 并检查我收到的 json 是否兼容。有没有办法从 C# 类生成正则表达式?

任何其他建议也会有所帮助。

谢谢

标签: c#regex

解决方案


使用 newtonsoft 的 JSON 模式验证器,这里有更多详细信息


        public class JsonSchemaController : ApiController
    {
        [HttpPost]
        [Route("api/jsonschema/validate")]
        public ValidateResponse Valiate(ValidateRequest request)
        {
            // load schema
            JSchema schema = JSchema.Parse(request.Schema);
            JToken json = JToken.Parse(request.Json);

            // validate json
            IList<ValidationError> errors;
            bool valid = json.IsValid(schema, out errors);

            // return error messages and line info to the browser
            return new ValidateResponse
            {
                Valid = valid,
                Errors = errors
            };
        }
    }

    public class ValidateRequest
    {
        public string Json { get; set; }
        public string Schema { get; set; }
    }

    public class ValidateResponse
    {
        public bool Valid { get; set; }
        public IList<ValidationError> Errors { get; set; }
    }


推荐阅读