java - SQL条件的Json表示
问题描述
有什么方法可以将 SQL 条件转换为 Json?我的意思是,我需要写这样的东西:
x > 5 and (y like '%b%' or z > 5) and b = true
作为杰森?
解决方案
您可以为此使用jOOQ和Gson。这是一个快速而肮脏的例子,说明它是如何工作的:
new Gson()
.newBuilder()
.setPrettyPrinting()
// Some jOOQ types can be serialised out of the box
// For others, you might have to register adapters explicitly:
.registerTypeHierarchyAdapter(
Field.class,
(JsonSerializer<Field<?>>) (s, t, ctx) -> new JsonPrimitive(s.getName()))
.create()
.toJson(DSL.using(SQLDialect.DEFAULT)
.parser()
.parseCondition("x > 5 and (y like '%b%' or z > 5) and b = true"),
System.out
);
以上打印:
{
"operator": "AND",
"conditions": [
{
"field1": "X",
"field2": "5",
"comparator": "GREATER"
},
{
"operator": "OR",
"conditions": [
{
"field1": "Y",
"field2": "%b%",
"comparator": "LIKE"
},
{
"field1": "Z",
"field2": "5",
"comparator": "GREATER"
}
]
},
{
"field1": "B",
"field2": "true",
"comparator": "EQUALS"
}
]
}
当然,这不是很向前兼容,因为它使用反射来访问 jOOQ 的内部。JSON 对象的名称(例如operator
, conditions
)可能随时更改,但对您来说可能仍然足够好。
未来的 jOOQ 版本可能会为其表达式树提供更稳定的 JSON 导出: https ://github.com/jOOQ/jOOQ/issues/9628
免责声明:我在 jOOQ 背后的公司工作。
推荐阅读
- javascript - 访问 iFrame 中的元素
- ajax - 将图像从 react-native 上传到 laravel REST API
- python-3.x - 用python更改xml文件中的子字符串
- c# - 使用元素作为名称在 foreach 循环中创建类
- django - 重定向到 django 中的同一页面
- c++ - 是否可以将 reinterpret_cast unsigned char 数组移植到 C++ 中仅包含 unsigned chars 成员的结构指针
- java - 使用数据库生成的字段创建 api 模型的最佳实践?
- cucumber - 如果我使用较新的 Cucumber 注释接口,如“io.cucumber.java.en.Given”,则找不到步骤定义
- scilab - 如何在scilab中绘制多项式根的区间
- python - 如何重塑张量流数据集结构?