【问题标题】:Spring JDBCTemplate : Construct JSON without special charactersSpring JDBCTemplate:构造没有特殊字符的 JSON
【发布时间】:2019-05-27 10:38:25
【问题描述】:

我正在从 postgreSQL DB 中读取表并在 json 对象中填充所有列及其值。

postgre 中的一列是 json 类型。所以输出有很多转义字符。如下所示的关键 dummykeyname。

 {
        "XY": "900144",
        "id": 1,
        "date": 1556167980000,
        "type": "XX50",
        "dummykeyname": {
            "type": "json",
            "value": "{\"XXXX\": 14445.0, \"YYYY\": 94253.0}"
        }
 }

我希望输出看起来像

  "value": "{"XXXX": 14445.0, "YYYY": 94253.0}"

我使用的代码是

JSONArray entities = new JSONArray();

var rm = (RowMapper<?>) (ResultSet result, int rowNum) -> {

while (result.next()) {
    JSONObject entity = new JSONObject();
    ResultSetMetaData metadata = result.getMetaData();
    int columnCount = metadata.getColumnCount() + 1;
    IntStream.range(1, columnCount).forEach(nbr -> {
      try {
        entity.put(result.getMetaData().getColumnName(nbr), result.getObject(nbr));
      } catch (SQLException e) {
        LOGGER.error(e.getMessage());
      }
    });
    entities.add(entity);
  }
  return entities;
};

使用的库:

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

请指导我哪里出错了。

【问题讨论】:

  • 存储在 db 中的 "dummykeyname" 列的值是一个 json {"XXXX": 14445.0, "YYYY": 94253.0}。我没有用双引号括起来。
  • jsonString.replace(/\\/g, "");

标签: java json postgresql resultset spring-jdbc


【解决方案1】:

采取不同的方法。

1) 首先创建所需列的pojo

  ex : if your table has 4 columns
         id, name, country, mobile create a class Employee and populate the class using rowmapper available in spring jdbc.

2) 创建一个 EmployeeList 类,其中包含 List ,将每个从 rowmapper 创建的 Employee 对象添加到声明的列表中。

3) 使用

a) ObjectMapper mapper = new ObjectMapper();
b) mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
c) mapper.writeValueAsString(EmployeeListobjects);

【讨论】:

  • 谢谢,我不能在这里使用任何 ORM。因为表名是动态的。我不能硬编码任何表名或列名。
猜你喜欢
  • 2018-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多