Obtain a real value from a ValueKind

442 Views Asked by At

I have a function that build a predicate to filter a query from the database based on a Json that it is coming from the request of the APIs. I opened other question about but not I know better the issue. With the new version of .NET, ASP.Net core uses inbuilt System.Text.Json based JsonConverter for binding the model from json input.

I have this code

public static Expression<Func<T, bool>> BuildPredicate<T>(
    this List<FilterParam> filter)
{
    Expression<Func<T, bool>> rtn = (t) => true;

    if (filter != null)
        foreach (var item in filter)
        {
            var predicate = BuildPredicate<T>(
                                 item.FieldName, item.Comparison, 
                                 item.Value);
            rtn = rtn.AndAlso(predicate);
        }

    return rtn;
}

So, the entire problem is on this line

var predicate = BuildPredicate<T>(
                    item.FieldName, item.Comparison, 
                    item.Value);

This is an example of the variable value in a related function.

The reason is the item.Value is System.Json.Text value and not a variable with the correct type. My function checks the type of the variable to make the comparison and expects the a valid type like int, string, date and so on.

What I need is at leat to identify the real type of the object, basically read the ValueKind and convert/cast the variable with thi type.

I searched online and I found some examples but it is not my case bacause the value changes. For example, I can get in input of the API something like

{
  "filterParams": [
    {
      "comparison": "Contains",
      "fieldName": "WordName",
      "value": "test"
    },
    {
      "comparison": "==",
      "fieldName": "ID",
      "value": 23
    }
  ]
}

In the Json above, value is in the first case a string and in the second case an int.

How can I convert the item.Value to a variable with the correct type? Is it possible to check the type of the ValueKind based on item.Value?

1

There are 1 best solutions below

0
On

I found how to get the type of the ValueKind and then convert the value in the right type.

public static object GetObjectValue(object obj)
{
    var typeOfObject = ((System.Text.Json.JsonElement)obj).ValueKind;

    switch (typeOfObject)
    {
        case JsonValueKind.Number:
            return long.Parse(obj.ToString());
        default:
            return obj.ToString();
    }
}