【问题标题】:How to return multiple columns as a JSON with other columns如何将多个列作为 JSON 与其他列一起返回
【发布时间】:2020-04-24 20:00:05
【问题描述】:

我有一个带有下一个方案的数据库,它使用 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、properties 和 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;

但是当我向邮递员发出请求时,它会返回:

[
    {
        "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"
    },
    ...
]

【问题讨论】:

  • 您只是从地震表中选择,对吗?您的预期结果是什么?
  • 是的,我编辑了问题以显示我的预期结果
  • SQL 查询和 Postman 请求之间似乎有额外的步骤,您是在开发 Web 应用程序吗?
  • 您似乎将结果集编码为 json。所以里面的json被双重编码了。
  • 你可以在 JSON 中做任何你能想象到的事情,你为什么不发挥你的想象力?

标签: java json postgresql spring-boot


【解决方案1】:

我发现这个 sql 创建了一个geojson file,所以当我调用方法时返回完美的字符串序列化。

SELECT row_to_json(fc) FROM ( 
 SELECT 'FeatureCollection' As type, 
  array_to_json(array_agg(f)) As features FROM 
  (SELECT 'Feature' As type, 
    ST_AsGeoJSON(lg.geom)::json As geometry, 
    row_to_json((SELECT l FROM (SELECT id, mag, time, felt, tsunami) As l )) As properties FROM terremotos As lg ) As f ) As fc;

【讨论】:

    【解决方案2】:

    为什么不在数据库上将整个转换为 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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-09
      • 2022-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-19
      相关资源
      最近更新 更多