c# - 如何验证 json 是类对象的正确表示?
问题描述
我收到了一些应该代表某个类的合法对象的 json。我希望验证确实如此。所以我反序列化了字符串,看看是否成功。这非常耗时,因为在某些情况下字符串会变得非常大并且其中有很多。因此,我正在寻找一种不同的方法。
我想从类的定义中创建一个 regExp 并检查我收到的 json 是否兼容。有没有办法从 C# 类生成正则表达式?
任何其他建议也会有所帮助。
谢谢
解决方案
使用 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; }
}
推荐阅读
- excel - 输入特定值时添加行 (Excel)
- python - Python Selenium-无法禁用第三方cookie阻止
- reactjs - 在 React 中填写复杂表单时设置对象属性的最佳方法是什么
- excel - 如果标题行不包含子字符串且范围不包含 #N/A,则求和
- javascript - 动画和改变状态时,动画消失(反应原生)
- html - 使绝对定位的孩子随他们的上级动态调整大小
- python - 在 python/selenium 中解析加载站点
- python - 我需要更改数据值的名称
- sql - 在 sql Query.neo 中需要帮助
- javascript - TypeError:“x”不可迭代