如何在Jackson中将JSON字符串解析为JsonNode?

2022-08-31 05:30:57

它应该如此简单,但我在尝试了一个小时后就找不到它了。

我需要获取一个 JSON 字符串,例如,解析为 .{"k1":v1,"k2":v2}JsonNode

JsonFactory factory = new JsonFactory();
JsonParser jp = factory.createJsonParser("{\"k1\":\"v1\"}");
JsonNode actualObj = jp.readValueAsTree();

java.lang.IllegalStateException: No ObjectCodec defined for the parser, can not deserialize JSON into JsonNode tree


答案 1

Richards答案略有不同,但可以采用字符串,因此您可以将其简化为:readTree

ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree("{\"k1\":\"v1\"}");

答案 2

您需要使用 :ObjectMapper

ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getJsonFactory(); // since 2.1 use mapper.getFactory() instead
JsonParser jp = factory.createJsonParser("{\"k1\":\"v1\"}");
JsonNode actualObj = mapper.readTree(jp);

有关创建解析器的更多文档,请参阅此处