[英]How can I read a json column from postgresql into java?
This postgresql query这个 postgresql 查询
SELECT array_to_json(array_agg(row_to_json(c))) FROM contacts c;
brings back a single column of type json.带回一个 json 类型的列。 Here is the working query in pgadmin...
这是 pgadmin 中的工作查询...
I would like to execute this same query from my Java server, which uses Jackson.我想从使用 Jackson 的 Java 服务器执行相同的查询。 What type should I read the response into?
我应该将响应读入什么类型? I have tried receiving the response as a PGobject variable, but after querying, I see that the variable is null.
我曾尝试将响应作为 PGobject 变量接收,但在查询后,我看到该变量为空。
I have also tried receiving the response into a String, but this throws the error:我也尝试将响应接收到字符串中,但这会引发错误:
java.lang.ClassCastException: class org.postgresql.util.PGobject cannot be cast to class java.lang.String (org.postgresql.util.PGobject is in unnamed module of loader 'app'; java.lang.String is in module java.base of loader 'bootstrap')
If the result is a json (or jsonb) you can use ResultSet.getString()
to read it.如果结果是 json(或 jsonb),您可以使用
ResultSet.getString()
来读取它。 Then pass that Jackson's ObjectMapper to convert it to something else.然后通过 Jackson 的 ObjectMapper 将其转换为其他内容。
Btw: you can simplify your aggregation to:顺便说一句:您可以将聚合简化为:
select jsonb_agg(to_jsonb(c))
from FROM contacts c;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.