gpt4 book ai didi

JAVA在postgres中存储字符串数组并从中检索JSON数据

转载 作者:行者123 更新时间:2023-12-01 11:24:38 25 4
gpt4 key购买 nike

我在数据库中的图像路径存储方面遇到了麻烦。如果我将路径作为字符串数组传递并将其存储在 PostgreSQL 中的 text[] 数组列中 - 我会收到一个文本值作为响应,如

"item_id":44,"item_phone":"432432423423","item_price":67676,"item_descr":"iojgoewjgoiwejgiewjgojoij","item_images":"{8f8161d3a6bdf6ahrth8fd35725356.jpg,11136408_101535465482739704_1782611644_o.jpg,15032923164db54t54d7ee548.jpg.thumb.jpg}","item_title":"ojreogreoihIGJEI","item_email":"jfeiwojiejowegj@ijfe"

“item_images”数组值位于响应中的“”中,因此我将其作为字符串值接收。但我想以 JSON 数组/列表的形式接收它

那么,组织数据库中的图像路径存储以最终以 JSON 列表/数组形式接收数据的更好方法是什么?

现在是这样的:

从 Post 接收数据的模型:

public class Item {
public String title;
public String descr;
public String phone;
public String email;
public String images[];
public int price;
}

这就是我在数据库中存储值的方式:

    PreparedStatement statement=conn.prepareStatement("INSERT INTO goods (item_title, item_descr, item_email, item_phone, item_images, item_price)\n" +
" VALUES ( ? , ? , ? , ? , ? , ? )");
int index=1;
statement.setInt(index++, item.condo_id);
statement.setString(index++,item.title.trim());
statement.setString(index++,item.descr.trim());
statement.setString(index++,item.email.trim());
statement.setString(index++,item.phone); //Assuming it is a String
statement.setArray(index++, conn.createArrayOf("text", item.images));
statement.setInt(index++,item.price); //Assuming it is a Double
int rowsUpdated = statement.executeUpdate();

这就是我以 JSONArray 形式返回这些值的方式:

Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("query to select all data from DB");

JSONArray jsonArray;
jsonArray = convertToJSON(rs);

public static JSONArray convertToJSON(ResultSet resultSet) throws Exception {
JSONArray jsonArray = new JSONArray();
while (resultSet.next()) {
int total_rows = resultSet.getMetaData().getColumnCount();
JSONObject obj = new JSONObject();
for (int i = 0; i < total_rows; i++) {
obj.put(resultSet.getMetaData().getColumnLabel(i + 1)
.toLowerCase(), resultSet.getObject(i + 1));
}
jsonArray.put(obj);
}
return jsonArray;
}

最佳答案

您可以尝试像这样修改convertToJSON()方法

            String name = resultSet.getMetaData().getColumnLabel(i + 1)
.toLowerCase();
int type = resultSet.getMetaData().getColumnType(i);
if (java.sql.Types.ARRAY == type) {
obj.put(name, resultSet.getArray(i + 1));
} else {
obj.put(name, resultSet.getObject(i + 1));
}

关于JAVA在postgres中存储字符串数组并从中检索JSON数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30931162/

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