yavuztor / JsonLogic.Net

JsonLogic implementation for .Net
MIT License
50 stars 21 forks source link

Exception in object Apply(JToken rule, object data); if we pass a dictionary containing a field that has an empty string. #32

Open Hassan-173732 opened 3 years ago

Hassan-173732 commented 3 years ago

`static void Main(string[] args) {

        // The data that the rule will run against. 
        //object data = new { MyNumber = 8 };
        var inputData = new Dictionary<string, object> { { "RRLFLD0128", "" } };

        // Rule definition retrieved as JSON text
        string jsonText = "{\"and\":[{\"<=\":[{\"var\":\"RRLFLD0128\"},25]}]}";

        // Parse json into hierarchical structure
        var rule = JObject.Parse(jsonText);

        // Create an evaluator with default operators.
        var evaluator = new JsonLogicEvaluator(EvaluateOperators.Default);

        // Apply the rule to the data.
        object result = evaluator.Apply(rule, inputData);

    }`

The inputData passed to the evaluator.Apply(rule, inputData) causes an exception because we are trying to compare a integer number to an empty string so the parser is unable to map the empty string to a valid number. For this I modified the method GenericArgsSatisfy in the EvaluateOperator class: Previously the return method was: return isAllText ? CheckCriteria(values.Cast<string>().ToArray(), criteriaText) : CheckCriteria(values.Select(a => a == null ? 0d : Double.Parse(a.ToString())).ToArray(), criteriaDouble); After Modification: return isAllText ? CheckCriteria(values.Cast<string>().ToArray(), criteriaText) : CheckCriteria(values.Select(a => a == null || (a is string && string.IsNullOrEmpty(a.ToString())) ? 0d : Double.Parse(a.ToString())).ToArray(), criteriaDouble); Now the function can parse the empty string to null instead of throwing and exception and the apply method produces the desired results.