我有一个具有下一个方案的数据库,它使用 postgressql 和 postgis 插件:
table_id | id | mag | time | felt | tsunami | geom
我有一个下一个 SQL 来选择一些行并将这些列作为 JSON 返回:
SELECT ROW_TO_JSON(t) as properties
FROM (
SELECT id, mag, time, felt, tsunami FROM earthquakes
) t
我想创建一个返回 table_id、属性和 geom 的 SQL 语句,例如:
SELECT table_id, properties, GeometryType(geom)
from earthquakes
如何以 JSON 形式返回具有属性的 table_id 和 geom?
编辑:
我创建了这个sql:
SELECT table_id,
row_to_json((SELECT d FROM (SELECT id, mag, time, felt, tsunami ) d)) AS properties,
GeometryType(geom)
FROM earthquakes ORDER BY table_id ASC;
但是当我向 postman 发出请求时,它会返回以下内容:
[
{
"table_id": 1,
"properties": {
"type": "json",
"value": "{\"id\" : \"ak16994521\", \"mag\" : 2.3}"
}
},
...
]
如何将值作为对象返回?
我的预期结果应该是:
[
{
"table_id": 1,
"properties": {"id" : "ak16994521", "mag" : 2.3}
},
...
]
Java 方法:
public List<Map<String, Object>> readTable(String nameTable) {
try {
String SQL = "SELECT table_id, GeometryType(geom) FROM " + nameTable + " ORDER BY table_id ASC;";
return jdbcTemplate.queryForList(SQL);
} catch( BadSqlGrammarException error) {
log.info("ERROR READING TABLE: " + nameTable);
return null;
}
}
此代码返回此 json:
[
{
"table_id": 1,
"geometrytype": "POINT"
},
{
"table_id": 2,
"geometrytype": "POINT"
},
....
]
我的预期结果应该是:
[
{
"table_id": 1,
"properties": {"id" : "ak16994521", "mag" : 2.3, "time": 1507425650893, "felt": "null", "tsunami": 0 },
"geometrytype": "POINT"
},
...
]
最佳答案
为什么不在数据库上将整个过程转换为 JSON?
SELECT json_agg(x) as json_values FROM (
SELECT
table_id,
row_to_json((select d from (select id, mag, time, felt, tsunami) d)) as properties,
GeometryType(geom)
FROM earthquakes
ORDER BY table_id ASC
) x;
关于java - 如何将多列与其他列一起以 JSON 形式返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59626274/