假设我查询一个列中包含rawjson
的表,或者使用如下子查询创建json:
select
p.name,
(select json_build_array(json_build_object('num', a.num, 'city', a.city)) from address a where a.id = p.addr) as addr
from person p;
我怎么能叫斯普林不要逃跑
但别管它?
到目前为止,它坚持给我这样的东西:
[{
name: "John",
addr: {
type: "json",
value: "{"num" : "123", "city" : "Luxembourg"}"
}
}]
最佳答案
这是有效的解决方案。
服务:
@Transactional(readOnly = true)
public String getRawJson() {
String sql = "select json_agg(row_to_json(json)) from ( "
+ "select "
+ "p.id, "
+ "p.name, "
+ "(select array_to_json(array_agg(row_to_json(c))) from ( "
+ " ... some subselect ... "
+ ") c ) as subq "
+ "from person p "
+ "where type = :type "
+ ") json";
MapSqlParameterSource params = new MapSqlParameterSource("type", 1);
return jdbcTemplate.queryForObject(sql, params, String.class);
}
控制器:
@ResponseBody
@GetMapping(value = "/json", produces = MediaType.APPLICATION_JSON_VALUE)
public String getRawJson() {
return miscService.getRawJson();
}
关键是
json_agg
和row_to_json / array_to_json
加上返回aString
的组合,以避免任何类型转换。关于sql - jdbcTemplate和原始JSON列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52709687/