简体   繁体   中英

Validate JSON serialization/deserialization to c# double

How can I have a schema that validates for the c# double?

The c# double can be: "NaN", "Infinity", "-Infinity". And this is important in our system, as there is logic depending on this values.

The JSON serialization/deserialization works perfectly. But what I can't validate is in the following example, if the JSON to deserialize contains some different string that cannot be converted to double. The validation passes and then it only crashes in the deserialization.

        [TestMethod]
        public void test3()
        {
            string json = @"{'A':'hello'}";

            // validate
            string myschemaJson = @"{
            'description': 'An employee', 'type': 'object',
            'properties':
                {
                   'A': {'allOf':[{'type':'string','enum': ['NaN','Infinity','-Infinity']}, {'type':'number'}]}
                }
            }";

            var schema = JsonSchema.Parse(myschemaJson);
            JObject myObjJson = JObject.Parse(json);

            // validation
            bool isValid = myObjJson.IsValid(schema, out IList<string> errors);

            isValid.Should().BeTrue(string.Join(",\n", errors.ToArray()));

            // deserialize
            var deserializeObject = JsonConvert.DeserializeObject<MySimpleObj>(json);
            Console.WriteLine(deserializeObject.A);
        }

        public class MySimpleObj
        {
            public double A { get; set; }
        }

You probably want to have a definition for csharpDouble (or similar) in which you define that it can be either

  • a number, or
  • one of the values "NaN" , "Infinity" , or "-Infinity"

For the first, you need

{ "type": "number" }

For the second, you want

{ "enum": [ "NaN", "Infinity", "-Infinity" ] }

So your schema would be

{
  ...
  "definitions": { // or $defs for draft 2019-09
    ...
    "csharpDouble": {
      "oneOf": [
        { "type": "number" },
        { "enum": [ "NaN", "Infinity", "-Infinity" ] }
      ]
    },
    ...
  },
  ...
}

This would allow instances like

{ "myDouble": 5.24, "myOtherDouble": "NaN" }

where both myDouble and myOtherDouble are properties constrained to validate against #/definitions/csharpDouble

Then in your deserializer, you may need to provide custom logic to deserialize the string values to the appropriate static fields on the double type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM