在 JSON 中,如何使用 C# 将相同的键值对递归添加到现有键之一



我一直在尝试不同的方法来实现这一目标, 我的输入是:

string statment = "(Entity.CIFNumber <> '3123' AND Entity.Country LIKE 'USA' AND (Entity.FYEMonth= 'May' OR Statement.ProgitBeforeTax= '123123' OR STATEMENT.NetSales <= 234234 OR STATEMENT.statementdatekey_ = '2019/07/01'))";

我想将其转换为 JSON:

"DataSetCommonQuery": {
"operator": "AND",
"rules": [
{
"field": "ENTITY.CIFNumber",
"condition": "<>",
"value": "3123"
},
{
"field": "ENTITY.Country",
"condition": "LIKE",
"value": "USA"
},
{
"operator": "OR",
"rules": [
{
"field": "ENTITY.FYEMonth",
"condition": "=",
"value": "May"
},
{
"field": "STATEMENT.ProfitBeforeTax",
"condition": ">=",
"value": 123123
},
{
"field": "STATEMENT.NetSales",
"condition": "<=",
"value": 234234
},
{
"field": "STATEMENT.statementdatekey_",
"condition": "=",
"value": "2019-07-01 12:00:00"
}
]
}
]
},

到目前为止我做了什么: 这些是我的课程:

public class DataSetCommonQuery
{
public string @operator { get; set; }
public List<Rule> rules = new List<Rule>(); 
}
public class Rule2
{
public string field { get; set; }
public string condition { get; set; }
public string value { get; set; }
}
public class Rule
{
public string field { get; set; }
public string condition { get; set; }
public string value { get; set; }
public string @operator { get; set; }
public List<Rule2> rules = new List<Rule2>(); //{ get; set; }
}

我尝试了递归,但无法访问或添加新运算符,规则对象到现有规则数组。我可能错过了一些非常明显的东西,但被困住了三天。

public class Base
{
}
public class Operation : Base
{
public string @operator { get; set; }
public List<Base> rules { get; set; }
}
public class Rule : Base
{
public string field { get; set; }
public string condition { get; set; }
public object value { get; set; }
}
Operation op = new Operation
{
@operator = "AND",
rules = new List<Base>
{
new Rule { field = "ENTITY.CIFNumber", condition = "<>", value = "3123" },
new Rule { field = "ENTITY.Country", condition = "LIKE", value = "USA" },
new Operation { @operator = "OR", rules = new List<Base>
{
new Rule { field = "ENTITY.FYEMonth", condition = "=", value = "May" },
new Rule { field = "STATEMENT.ProfitBeforeTax", condition = ">=", value = 123123 },
new Rule { field = "STATEMENT.NetSales", condition = "<=", value = 234234 },
new Rule { field = "STATEMENT.statementdatekey_", condition = "=", value = new DateTime(2019, 7, 1, 12, 0, 0) }
}
}
}
};
string json = JsonConvert.SerializeObject(op, Formatting.Indented);

生成的 json

{
"operator": "AND",
"rules": [
{
"field": "ENTITY.CIFNumber",
"condition": "<>",
"value": "3123"
},
{
"field": "ENTITY.Country",
"condition": "LIKE",
"value": "USA"
},
{
"operator": "OR",
"rules": [
{
"field": "ENTITY.FYEMonth",
"condition": "=",
"value": "May"
},
{
"field": "STATEMENT.ProfitBeforeTax",
"condition": ">=",
"value": 123123
},
{
"field": "STATEMENT.NetSales",
"condition": "<=",
"value": 234234
},
{
"field": "STATEMENT.statementdatekey_",
"condition": "=",
"value": "2019-07-01T12:00:00"
}
]
}
]
}

最新更新