【问题标题】:C#: JSON Schema validation and JSON.stringifyC#:JSON 模式验证和 JSON.stringify
【发布时间】:2016-05-26 05:22:59
【问题描述】:

[对不起我糟糕的英语]

现在我使用 JSON.Net,但它对数字类型的验证过于严格。 问题是 JSON.stringify 看不到“数字”和“整数”之间的区别,他只有“数字”。 事实证明,如果你序列化 1.0,输出将只是 1(整数),而 JSON.Net Validator 将是“数字”。

我不想在“int”中分配“数字”,我想在“float”中分配“整数”。 示例架构:

{
  "type": "object",
  "properties": {
    "singleField": {
      "type": "number"
    }
  }
}

示例 JSON:

{
  "singleField":1//it is 1.0 after JSON.stringify
}

验证将失败。

最合适的解决方案是在客户端使用架构,但没有这种可能性。 我没有绑定到 JSON.Net,所以要做出任何决定。 我使用 .net 3.5。

【问题讨论】:

    标签: c# validation .net-3.5 json.net jsonschema


    【解决方案1】:

    原因在于旧版本的 JSON.Net。此代码有效:

    using Newtonsoft.Json;
    using Newtonsoft.Json.Schema;
    using Newtonsoft.Json.Schema.Generation;
    
    public class JSSchemaTest
    {
        class TestClass
        {
            public float field = 20;
        }
        JSchemaGenerator generator = new JSchemaGenerator();
        JsonSerializer serializer = new JsonSerializer();
    
        public void Run()
        {
            JSchema schema = generator.Generate(typeof(TestClass));
            JsonTextReader reader = new JsonTextReader(new System.IO.StringReader("{field: 2}"));
            JSchemaValidatingReader validatingReader = new JSchemaValidatingReader(reader);
            validatingReader.Schema = schema;
            TestClass res = serializer.Deserialize<TestClass>(validatingReader);
        }
    }
    

    使用 Json.NET 8.0.2,Json.NET Schema 2.0.2。

    UPD:作为替代方案,在旧版本的 JSON.Net 中,我们可以对文件 JsonSchemaGenerator 进行小修改。搜索此行:

    internal static bool HasFlag(JsonSchemaType? value, JsonSchemaType flag)
    

    并将其“返回”替换为拥有:

    return (flag == JsonSchemaType.Integer && value == JsonSchemaType.Float) ? true : ((value & flag) == flag);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-22
      • 2011-06-08
      • 2023-02-01
      • 2020-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多