gpt4 book ai didi

java - 如何在 java 中从 postgres 检索和使用 json 列以及非 json 列?

转载 作者:行者123 更新时间:2023-11-29 13:51:14 24 4
gpt4 key购买 nike

我正在尝试从 postgres 数据库中读取数据,其中有一列为 json 类型。而其他列不是 json。虽然我尝试使用一些示例和 stackoverflow 代码,但它给出了错误。这个我试过了

ObjectMapper mapper = new ObjectMapper();
String json = (rs.getString("topic_data"));
Map<String, Object> map = new HashMap<String, Object>();
// convert JSON string to Map
map = mapper.readValue(json, new TypeReference<Map<String, String>>() {});

出现这个错误:

Dao com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_ARRAY token
at [Source: {"topicHeader": "attendant windows", "words": [{"percentage": 0.1322331750852289, "word": "windows"}, {"percentage": 0.07222296435182111, "word": "get"}, {"percentage": 0.07221384639035615, "word": "computer"}, {"percentage": 0.07221264897351826, "word": "instead"}, {"percentage": 0.0722068233704654, "word": "just"}, {"percentage": 0.07202521418513595, "word": "still"}, {"percentage": 0.07181489746918468, "word": "attendant"}, {"percentage": 0.012222238496667995, "word": "don"}, {"percentage": 0.012126611197220477, "word": "really"}, {"percentage": 0.012109084263926815, "word": "ie"}, {"percentage": 0.012104725488616788, "word": "went"}, {"percentage": 0.01210188511739723, "word": "order"}, {"percentage": 0.012101477029454613, "word": "service"}, {"percentage": 0.012100753482874852, "word": "deal"}, {"percentage": 0.012100113702598862, "word": "professional"}, {"percentage": 0.012099577741692897, "word": "store"}, {"percentage": 0.012099153533334564, "word": "purchase"}, {"percentage": 0.01209459547306794, "word": "website"}, {"percentage": 0.01209311873816971, "word": "make"}, {"percentage": 0.01208934633126715, "word": "buy"}]}; line: 1, column: 36] (through reference chain: java.util.LinkedHashMap["words"])`

我的 json 列是这样的:

{
"topicHeader":"header",
"words":[{
"word":"hello",
"percentage":12.14
},{
"word":"hi",
"percentage":22.14
}]
}

解决问题的最佳方法是什么?

最佳答案

如消息所述,[{ "word":"hello", "percentage":12.14 },{ "word":"hi", "percentage":22.14 }] 是不是字符串。

所以你应该使用合适的自定义类:

class Foo {
private String topicHeader;
private List<Bar> words;
// getter, setter, etc
}

class Bar {
private String word;
private double percentage;
// getter, setter, etc
}

然后 Foo foo = mapper.readValue(json, Foo.class) 并使用 foo

关于java - 如何在 java 中从 postgres 检索和使用 json 列以及非 json 列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40888244/

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