如何在 Jackson 中将 JSON 字符串解析为 JsonNode?
本来应该很简单的,但是我试了一个小时还是找不到。
我需要获取一个 JSON 字符串,例如 {"k1":v1,"k2":v2}
,解析为 JsonNode
。
JsonFactory factory = new JsonFactory();
JsonParser jp = factory.createJsonParser("{\"k1\":\"v1\"}");
JsonNode actualObj = jp.readValueAsTree();
给出
java.lang.IllegalStateException:没有为解析器定义 ObjectCodec,无法将 JSON 反序列化为 JsonNode 树
It should be so simple, but I just cannot find it after being trying for an hour.
I need to get a JSON string, for example, {"k1":v1,"k2":v2}
, parsed as a JsonNode
.
JsonFactory factory = new JsonFactory();
JsonParser jp = factory.createJsonParser("{\"k1\":\"v1\"}");
JsonNode actualObj = jp.readValueAsTree();
gives
java.lang.IllegalStateException: No ObjectCodec defined for the parser, can not deserialize JSON into JsonNode tree
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
与理查兹的答案略有不同,但 readTree 可以采用字符串,因此您可以将其简化为:
A slight variation on Richards answer but
readTree
can take a string so you can simplify it to:您需要使用
ObjectMapper
:有关创建解析器的更多文档可以找到 这里。
You need to use an
ObjectMapper
:Further documentation about creating parsers can be found here.
第三种变体:
A third variant:
理查德的回答是正确的。或者,您也可以创建一个
MappingJsonFactory
(在org.codehaus.jackson.map
中),它知道在哪里可以找到ObjectMapper
。您收到的错误是因为常规JsonFactory
(来自core
包)不依赖于ObjectMapper
(位于mapper< /代码> 包)。
但通常您只使用
ObjectMapper
而不必担心JsonParser
或其他低级组件 - 如果您想要对流的部分数据进行数据绑定,或者进行低级处理。Richard's answer is correct. Alternatively you can also create a
MappingJsonFactory
(inorg.codehaus.jackson.map
) which knows where to findObjectMapper
. The error you got was because the regularJsonFactory
(fromcore
package) has no dependency toObjectMapper
(which is in themapper
package).But usually you just use
ObjectMapper
and do not worry aboutJsonParser
or other low level components -- they will just be needed if you want to data-bind parts of stream, or do low-level handling.老问题的新方法。
对于复杂对象来说,适用于 java 9+ 的解决方案
更具可读性和可维护性。埃杰
New approach to old question.
A solution that works from java 9+
is more readable and maintainable for complex objects. Ej
在科特林中:
In kotlin: