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
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
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