skip to Main Content

I know I can check wether is a string is a valid JSON-formatted string using parsing functions and catching exceptions. But what I need is a bit more than that too.

I need to check if a string that comes in abides a certain model in JSON format.

E.g. I have this class

class MyClass {
  public String Key1 { get; set; }
  public List<MyClass2> Key2 { get set; }
  public int Key3 { get set; }
}

class MyClass2 {
  public int Key4 { get; set; }
}

and the following string s1 comes in

{
  "Key1": "Hello",
  "Something": "World",
  "Key2": [
     { "Key4": 100 }
  ],
  "Key3": 2
}

Although s1 IS a validly formatted JSON string, it does not abide by the structure of MyClass1 since it has a property Something that is not a property of MyClass1. If however I receive the following string s2

{
  "Key1": "Hello",
  "Key2": [
     { "Key4": 100 }
  ]
}

then this would be valid for me even though there are properties missing. Formally put, the given properties must be exactly a subset of the model’s properties.

How could I achieve this in .NET? Note that MyClass could be generic so I cannot hard check for names.

2

Answers


  1. Simply, you could make a function to foreach on each property of your incoming object and if the whole object doesn’t match your ‘MyClass’ return "False"

    Kind Regards

    Login or Signup to reply.
  2. JSON Schema is a thing and, I would argue, should be used to validate JSON.

    There are a number of different implementations and a few of them are for .NET. There’s even one from NewtonSoft – JSON.Net Schema although it’s not completely free!

    An example using JsonSchema.Net

    using Json.Schema;
    using Json.Schema.Generation;
    using Json.Schema.Serialization;
    
    var json = @"{
      ""Key1"": ""Hello"",
      ""Something"": ""World"",
      ""Key2"": [
         { ""Key4"": 100 }
      ],
      ""Key3"": 2
    }";
    
    var schema = new JsonSchemaBuilder()
        .FromType<MyClass>()
        // Fail the validation if there any additional properties.
        .AdditionalProperties(JsonSchema.False)
        .Build();
    
    var evaluationResults = schema.Evaluate(System.Text.Json.JsonDocument.Parse(json));
    
    if (!evaluationResults.IsValid){
        // Log/throw an error here.
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search