首页 > 解决方案 > SQL条件的Json表示

问题描述

有什么方法可以将 SQL 条件转换为 Json?我的意思是,我需要写这样的东西:

x > 5 and (y like '%b%' or z > 5) and b = true

作为杰森?

标签: javasqljson

解决方案


您可以为此使用jOOQGson。这是一个快速而肮脏的例子,说明它是如何工作的:

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 背后的公司工作。


推荐阅读