Search code examples
c#.net-corerule-enginejsonserializer

Attempting simple proof of concept of microsoft / RulesEngine but getting JsonSerializationException


I'm assuming I've made a stupid mistake here, but wondering if someone could assist?

I am trying out the following library:

Install-Package RulesEngine -Version 3.2.0

My rules.json is as follows:

[
  {
      "WorkflowName": "DeliverToMatchingSuburb",
      "Rules": [
        {
          "RuleName": "MatchingSuburb",
          "Expression": "customer.PostCode == location.PostCode"
        }
      ]
  }
]

My code:

    string[] readText = File.ReadAllLines("rules.json");
    Customer c = new Customer();
    Pharmacy p = new Pharmacy();
    var pharmacies = p.GetLocations();
    var customers = c.GenerateCustomers();

    var re = new RulesEngine.RulesEngine(readText, null);

My attempt to pass 'readText' into the RulesEngine however gives me the following exception?

Newtonsoft.Json.JsonSerializationException: 'Unexpected end when reading JSON. Path '', line 1, position 1.'

The exception occurs at this line: var re = new RulesEngine.RulesEngine(readText, null);

  • I have checked that the JSON is valid by using an online JSON validator.
  • I've also tried adding curly braces at the top and bottom.
  • I've even tried copy/pasting the example rules JSON from the documentation here https://github.com/microsoft/RulesEngine#how-to-use-it (knowing it won't work but should at least pass the step of creating the RulesEngine) but that too fails with the same error.

Solution

  • The expectation for the RulesEngine(string[], ILogger, ReSettings) constructor is that each element of the string array is a complete JSON object. In your case, you've provided just a single line per array element.

    Given that your text file already contains a collection of rules, you should deserialize it yourself, and pass the deserialized collection into the constructor accepting a WorkflowRules[]:

    string json = File.ReadAllText("rules.json");
    var rules = JsonConvert.DeserializeObject<WorkflowRules[]>(json);
    var engine = new RulesEngine.RulesEngine(rules);