Java 如何将 JsonNode 转换为 ObjectNode

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

How to convert JsonNode to ObjectNode

javajson

提问by Mr. Noddy

I have a com.fasterxml JsonNodeobject with some data. I need to do some manipulation on its data. I googled for answer but didn't got it properly. Can you please suggest me how to manipulate JsonNode data. I have also tried to convert JsonNodeto ObjectNodeas follows

我有一个com.fasterxml JsonNode带有一些数据的对象。我需要对其数据进行一些操作。我用谷歌搜索答案,但没有得到正确的答案。您能否建议我如何操作 JsonNode 数据。我也试图转换JsonNodeObjectNode如下

ObjectNode objectNode = (ObjectNode)filterJson;

but its giving following exception....

但它给出了以下例外......

java.lang.ClassCastException: com.fasterxml.Hymanson.databind.node.TextNode cannot be cast to 
com.fasterxml.Hymanson.databind.node.ObjectNode

please help!!

请帮忙!!

采纳答案by Mr. Noddy

Finally, I got the solution as follows...

最后,我得到了以下解决方案......

JsonNode jsonNode = Json.toJson("Json String");
ObjectNode node = (ObjectNode) new ObjectMapper().readTree(jsonNode.asText());
//perform operations on node
jsonNode = (JsonNode) new ObjectMapper().readTree(node.toString());

or another one as below...

或另一种如下...

ObjectNode node = (ObjectNode) new ObjectMapper().readTree("Json String")
//perform operations on node
jsonNode = (JsonNode) new ObjectMapper().readTree(node.toString());

but I don't know if this is good approach or not ? If there is any better than above, please let me know. Thank you!

但我不知道这是否是好方法?如果有比上面更好的,请告诉我。谢谢!

回答by Daniele Licitra

You can convert a JsonNodein an ObjectNodein this simple way:

您可以JsonNode通过ObjectNode这种简单的方式将 a 转换为an :

ObjectNode objectNode = jsonNode.deepCopy();

Available from Hymanson 2.0and tested with Hymanson 2.4.0

可从 Hymanson 2.0 获得并使用 Hymanson 2.4.0 进行测试

回答by Daejong Lin

I try it some times, it will be ok! You only define a Student Classto map the properties. Then you could convert the jsonNodeto StudentObject.

我试了几次,会好的!您只需定义一个Student Class来映射属性。然后你可以将对象转换jsonNodeStudent对象。

Student student = objectMapper.convertValue(jsonNode1, Student.class);

Student student = objectMapper.convertValue(jsonNode1, Student.class);

I think this will be suitable for your need!

我认为这将适合您的需要!

回答by dozer

I had this error too although in my case it was a stupid mistake. I accidentally imported org.codehaus.Hymanson.node.ObjectNodeinstead of com.fasterxml.Hymanson.databind.node.ObjectNode. Using the Hymanson ObjectNode fixed the issuse.

我也有这个错误,尽管在我的情况下这是一个愚蠢的错误。我不小心导入org.codehaus.Hymanson.node.ObjectNode而不是com.fasterxml.Hymanson.databind.node.ObjectNode. 使用 Hymanson ObjectNode 解决了这个问题。