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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3653996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 03:12:59  来源:igfitidea点击:

How to parse a JSON string into JsonNode in Hymanson?

javajsonparsingHymanson

提问by fadmaa

It should be so simple, but I just cannot find it after being trying for an hour #embarrasing.

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

I need to get a JSON string, for example, {"k1":v1,"k2":v2}, parsed as a JsonNode.

我需要获取一个 JSON 字符串,例如{"k1":v1,"k2":v2},解析为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

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

采纳答案by slashnick

A slight variation on Richards answer but readTreecan take a string so you can simplify it to:

理查兹答案略有变化,但readTree可以采用字符串,因此您可以将其简化为:

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

回答by Richard Fearn

You need to use an ObjectMapper:

您需要使用一个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);

Further documentation about creating parsers can be found here.

可以在此处找到有关创建解析器的更多文档。

回答by StaxMan

Richard's answer is correct. Alternatively you can also create a MappingJsonFactory(in org.codehaus.Hymanson.map) which knows where to find ObjectMapper. The error you got was because the regular JsonFactory(from corepackage) has no dependency to ObjectMapper(which is in the mapperpackage).

理查德的回答是正确的。或者,您也可以创建一个MappingJsonFactory(in org.codehaus.Hymanson.map),它知道在哪里可以找到ObjectMapper. 您得到的错误是因为常规JsonFactory(来自core包)不依赖于ObjectMapper(在mapper包中)。

But usually you just use ObjectMapperand do not worry about JsonParseror other low level components -- they will just be needed if you want to data-bind parts of stream, or do low-level handling.

但通常你只是使用ObjectMapper而不用担心JsonParser其他低级组件——如果你想对流的部分进行数据绑定,或者进行低级处理,它们将是必需的。

回答by qerub

A third variant:

第三种变体:

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

回答by pdxleif

import com.github.fge.Hymanson.JsonLoader;
JsonLoader.fromString("{\"k1\":\"v1\"}")
== JsonNode = {"k1":"v1"}