Java 将 JsonNode 对象转换为 Map

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26766256/
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-11 03:14:51  来源:igfitidea点击:

Convert JsonNode object to Map

javajsonHymansonplayframework-2.2

提问by visc

I have a C# program that sends me a json object. I'm making a Java Play website to capture the POST data. I get the correct data as a JsonNodeobject but need to convert it into a Map.

我有一个 C# 程序,它向我发送一个 json 对象。我正在制作一个 Java Play 网站来捕获 POST 数据。我获得了正确的数据作为JsonNode对象,但需要将其转换为Map.

I'm using com.fasterxml.Hymanson.databind.JsonNode

我正在使用 com.fasterxml.Hymanson.databind.JsonNode

Here is where I correctly capture the JsonNode object:

这是我正确捕获 JsonNode 对象的地方:

public static Result index() {
    JsonNode json = request().body().asJson();
}

Now that I have the object I need to figure out how to convert it into a Mapso that I can so some magic on it. Later I'll want to convert the Mapback into a json object to be sent in the response.

现在我有了这个对象,我需要弄清楚如何将它转换成 aMap以便我可以对它施展魔法。稍后我想将Map返回转换为要在响应中发送的 json 对象。

I've been looking in the documentation, but the methods available don't scream as the solution.

我一直在查看文档,但可用的方法并没有作为解决方案而尖叫。

Here is the documentation I've been referencing for this particular JsonNodeobject: http://fasterxml.github.io/Hymanson-databind/javadoc/2.2.0/com/fasterxml/Hymanson/databind/JsonNode.html

这是我为这个特定JsonNode对象引用的文档:http: //fasterxml.github.io/Hymanson-databind/javadoc/2.2.0/com/fasterxml/Hymanson/databind/JsonNode.html

采纳答案by mhogerheijde

Got here trying to find the answer myself. Dug a little deeper and found a bit the answer here

来到这里试图自己找到答案。挖得更深一点,在这里找到了一点答案

Basically just use the ObjectMapperto convert the value for you:

基本上只需使用ObjectMapper为您转换值:

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> result = mapper.convertValue(jsonNode, new TypeReference<Map<String, Object>>(){});