【问题标题】:Match conditions with property name and value from JSON data将条件与 JSON 数据中的属性名称和值匹配
【发布时间】:2015-11-08 09:06:18
【问题描述】:

假设我在具有这种结构的 SQL 数据库中有一个包含规则的表:

Rule         Conditions                                 Action
------------`------------------------------------------ ---------------------
1            {"country": "USA", "state": "NY"}          DoActionOne
2            {"country": "France", "department": "55"}  DoActionTwo

这些规则适用于我的用户。所以州、国家、部门是我可以在我的用户或用户地址定义中找到的属性。但这些规则可以是别的东西。它可能是我的用户创建日期或我现在不期望的日期。

如何加载此条件字符串并与我的用户一起评估每个规则和每个条件?我知道如何从我的数据库中检索数据。我使用实体框架,但我不知道如何在查询或 JSON 对象中转换字符串。

'NOT TESTED
For Each rule As Rule In dbContext.rules
    'Load condition one
    Dim condition = rule.Conditions.???
    If (MyUser[condition.Name] = condition.Value)
        ' DoAction
    End If
Next

【问题讨论】:

    标签: json vb.net linq


    【解决方案1】:

    您可以使用一点Reflection 来实现这一点。

    假设这是您的 UserAddress 课程

    public class UserAddress
    {
        public string Country { get; set; }
        public string State { get; set; }
        public int Department { get; set; }
        //other properties
    }
    

    然后,假设您已经正确阅读了JSON 并以字符串对的形式获得了规则列表(例如“国家”和“法国”、“部门”和“55”等),您可以编写规则检查代码为

    var userAdd = new UserAddress { Country = "France", Department = 55, State = "SomeState" };
    bool allRulesChecked = true;
    foreach (var rule in rules)
    {
        var property = typeof(UserAddress).GetProperty(rule.Key, System.Reflection.BindingFlags.IgnoreCase | 
                                    System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Instance);
        if (property != null && property.GetValue(userAdd).ToString() != rule.Value.ToString())
        {
            allRulesChecked = false;
            break;
        }
    }
    

    注意,它不适用于复杂类型。

    【讨论】:

      猜你喜欢
      • 2021-12-03
      • 2021-10-14
      • 2015-04-29
      • 2013-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-13
      相关资源
      最近更新 更多