1
votes

I need a way to define a filter for an unknown type. The filter should be able to check an incoming JSON object against that filter. The filter should be JSON-serializable as well.

For example a filter that defines:

  • The object should have a property Prop1 with value Val1
  • It should have a property Prop2 that has an object as value, with SubProp1 equal to Val2
  • It should have a Prop3 that contains one of these values: [1, 2, 3]

Does something like this already exist, or will I need to implement this from scratch?

1
Just realized I may get far with JSON schema. Maybe not 100% what I need, but it's a start.Coder14
Can you show an example how the filter string would look like?tymtam
Well, the exact syntax is yet to be defined. I'm looking for some library that does something like this. An example in words: An object with a property Links which contains objects which have a property ID. The value of this ID property should be an item of this list: [1, 2, 42, 89, 16]. This is of course only a very small example. In reality, the filter will contain many properties, which hold on its own complex types, with many properties.Coder14
You may want to use a JSON Schema. See the tag jsonschema. Newtonsoft has schema support as a paid extra.dbc

1 Answers

1
votes

If your json serialiser is Json.NET then a validate method that uses JObject should do the job (official examples here).

For example:

bool Validate(string json) 
{
    JObject rss = JObject.Parse(json);
    if(((string)rss["Prop1"]) != "Val1" ) return false;
    ... 

For the new .NET Core/5 System.Text.Json serialiser, a similar solution could be build with JsonDocument.Parse. An example is shown in Try the new System.Text.Json APIs.