Is there any method to convert a SQL condition to Json? I mean, I need to write something like this:
x > 5 and (y like '%b%' or z > 5) and b = true
as Json?
You could use jOOQ and Gson for that. Here's a quick and dirty example of how that could work:
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
);
The above prints:
{
"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"
}
]
}
Of course, this is not very forward compatible, because it uses reflection to access jOOQ's internals. The names of your JSON objects (eg operator
, conditions
) might change at any time, but it may still be good enough for you.
A future jOOQ version might offer more stable JSON exports of its expression tree: https://github.com/jOOQ/jOOQ/issues/9628
Disclaimer: I work for the company behind jOOQ.
Recently I found and used JsonLogic. It is very good approach as well. https://jsonlogic.com/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.