in

How would you handle deserializing a query filter class?


assume you have JSON data that should be deserialized to a class that represents a search expression. In this case, the expression class has three members: Left, Operator, and Right. Left and Right can either be a literal (i.e. foo, 123, false), or, they can be another expression, thus, they are defined as a generic object. The Operator can be one of many expected operators such as And, Or, etc.

For instance:

public class Expr
{
  public object Left { get; set; } = null;
  public OperatorEnum Operator { get; set; } = OperatorEnum.Equals;
  public object Right { get; set; } = null;
}

I’m having a hard time figuring out how to appropriately handle deserialization in cases where Left is an Expr, or, Left is a string. Consider these two examples:

Example 1: Left is a string

{
  "Left": "Amount",
  "Operator": "GreaterThan",
  "Right": 100.00
}

Example 2: Left is an embedded expression

{
    "Left": {
        "Left": {
            "Left": "Amount",
            "Operator": "GreaterThan",
            "Right": 100.00
        },
        "Operator": "And",
        "Right": {
            "Left": "NameOnCard",
            "Operator": "Contains",
            "Right": "Smith"
        }
    },
    "Operator": "And",
    "Right": {
        "Left": {
            "Left": "Brand",
            "Operator": "Equals",
            "Right": "Visa"
        },
        "Operator": "Or", 
        "Right": {
            "Left": "Brand",
            "Operator": "Equals",
            "Right": "Mastercard"
        }
    }
}

In testing this out with JSON.NET, I found that it, for any case where Left or Right are nested Expr objects, will leave them as JObjects (which can’t be cast). Ideally I’d prefer this code not have a serializer as a dependency (i.e. to manually convert JObject to Expr), but I can’t figure out how to convert/cast from JObject (when using Newtonsoft.Json) to type Expr. I assume I’ll encounter a similar situation with System.Text.Json, but have not tried.

So my question is… How do I ensure that the properties Left and Right are of type Expr after deserialization instead of the intermediary types used by the deserializer?

Note: I’ve tried using the [OnDeserialized()] attribute along with checking/casting Left and Right, which is where I’m running into a (very much expected) System.InvalidCastException exception.



Source: https://stackoverflow.com/questions/70537137/how-would-you-handle-deserializing-a-query-filter-class

A small module for creating a card deck, used for making card games

Can i set a custom tag and a custom value in laravel component?