{"groupOp":"OR","groups":[{"groupOp":"AND","rules":[{"field":"F_Gender","op":"eq","data":"0"}],"groups":[]}],"rules":[{"field":"F_DepartmentId","op":"eq","data":"13365d1b-92f2-4dc7-98a0-9e9c9ffdafdf"},{"field":"F_DepartmentId","op":"eq","data":"23ac3ac1-097f-4007-8bd2-20fea87fe377"}]} c# 怎么封装解析以上字符串 并返回拼接好得SQL
时间: 2023-07-06 07:43:32 浏览: 107
可以封装一个静态方法,将 JSON 字符串作为参数传入,返回拼接好的 SQL 语句。以下是一个可能的实现:
```csharp
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
public static class QueryParser
{
public static string Parse(string jsonString, string tableName)
{
dynamic query = JsonConvert.DeserializeObject(jsonString);
string where = BuildWhereClause(query.rules, query.groupOp);
string subqueries = BuildSubqueries(query.groups, query.groupOp, tableName);
if (subqueries != "") where += $" AND id IN ({subqueries})";
string sql = $"SELECT * FROM {tableName} WHERE {where}";
return sql;
}
private static string BuildWhereClause(dynamic rules, string groupOp)
{
string where = "";
foreach (var rule in rules)
{
string field = rule.field;
string op = rule.op;
string data = rule.data;
if (where != "") where += $" {groupOp} ";
switch (op)
{
case "eq":
where += $"{field} = '{data}'";
break;
// 其他比较操作符
}
}
return where;
}
private static string BuildSubqueries(dynamic groups, string groupOp, string tableName)
{
string subqueries = "";
foreach (var group in groups)
{
if (subqueries != "") subqueries += $" {groupOp} ";
string subwhere = BuildWhereClause(group.rules, group.groupOp);
if (subwhere != "") subqueries += $"(SELECT * FROM {tableName} WHERE {subwhere})";
}
return subqueries;
}
}
```
这个方法接受两个参数:JSON 字符串和表名。它会先将 JSON 字符串解析为对象,然后调用两个私有方法分别生成 WHERE 子句和子查询部分,最后拼接成完整的 SQL 语句并返回。需要注意的是,这个方法没有对 SQL 注入进行防护,使用时应当谨慎。
阅读全文