【问题标题】:Attempting simple proof of concept of microsoft / RulesEngine but getting JsonSerializationException尝试简单的 microsoft / RulesEngine 概念证明但得到 JsonSerializationException
【发布时间】:2021-09-04 06:20:21
【问题描述】:

我假设我在这里犯了一个愚蠢的错误,但想知道是否有人可以提供帮助?

我正在尝试以下库:

Install-Package RulesEngine -Version 3.2.0

我的rules.json如下:

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

我的代码:

    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);

我尝试将“readText”传递给规则引擎却给了我以下异常?

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

异常发生在这一行:var re = new RulesEngine.RulesEngine(readText, null);

  • 我使用在线 JSON 检查了 JSON 是否有效 验证器。
  • 我还尝试在顶部添加花括号和 底部。
  • 我什至尝试从 文档在这里 https://github.com/microsoft/RulesEngine#how-to-use-it(知道 它不起作用,但至少应该通过创建 RulesEngine),但同样的错误也失败了。

【问题讨论】:

  • 最好提供静态方法RulesEngine.RulesEngine(的代码
  • @RomanIeromenko:这是他们正在使用的库的一部分。它位于github.com/microsoft/RulesEngine/blob/main/src/RulesEngine/…,但 OP 不知道这一点并非完全不合理。
  • 抱歉伙计们,我应该提到在我的代码 sn-p 等中使用该库的位置。

标签: c# .net-core rule-engine jsonserializer


【解决方案1】:

RulesEngine(string[], ILogger, ReSettings) 构造函数的期望是字符串数组的每个元素都是一个完整的 JSON 对象。在您的情况下,您只为每个数组元素提供了一行。

鉴于您的文本文件已经包含规则集合,您应该自己反序列化它,并将反序列化的集合传递给接受WorkflowRules[]的构造函数:

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

【讨论】:

  • 谢谢乔恩,我认为让我失望的是构造函数期望字符串 [],所以我认为出于某种原因,我什至需要将单个规则作为字符串 [] 传递。不知何故,我错过了超载。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-12
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 2012-04-20
  • 2014-06-12
相关资源
最近更新 更多