gpt4 book ai didi

java - Spring JDBCTemplate : Construct JSON without special characters

转载 作者:行者123 更新时间:2023-12-02 05:11:16 24 4
gpt4 key购买 nike

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

postgre 中的一列是 json 类型。所以输出有很多转义字符。就像下面的 key 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;

请指导我哪里出错了。

最佳答案

采取不同的方法。

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);

关于java - Spring JDBCTemplate : Construct JSON without special characters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56324428/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com