Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an ObjectNode from JSON string

Tags:

java

json

jackson

How do I create a ObjectNode from a string using Jackson?

I tried:

ObjectNode json = new ObjectMapper().readValue("{}", ObjectNode.class);

But get

Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Conflicting setter definitions for property "type": jdk.nashorn.internal.ir.Symbol#setType(1 params) vs jdk.nashorn.internal.ir.Symbol#setType(1 params)

I want to be able to read a JSON string the add/modify some values.

like image 967
Petah Avatar asked May 06 '15 22:05

Petah


People also ask

How do you parse JSON strings into Jackson JsonNode model?

The process of parsing JsonString into JsonNode is very simple. We simply create an instance of ObjectMapper class and use its readTree() method in the following way: String str = "{\"proId\":\"001\",\"proName\":\"MX Pro 20\",\"price\":\"25k\"}"; ObjectMapper map = new ObjectMapper();

How do you create an ArrayNode?

Create an empty JSON Array To create a JSON Object we used createObjectNode() method of ObjectMapper class. Similarly to create JSON Array we use createArrayNode() method of ObjectMapper class. createArrayNode() will return reference of ArrayNode class.

Can JSON Object convert to String?

Stringify a JavaScript ObjectUse the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.

How does ObjectMapper read JSON data?

Read Object From JSON via URL ObjectMapper objectMapper = new ObjectMapper(); URL url = new URL("file:data/car. json"); Car car = objectMapper. readValue(url, Car. class);


2 Answers

You are using the wrong import.

It should be

com.fasterxml.jackson.databind.node.ObjectNode

Not:

jdk.nashorn.internal.ir.ObjectNode
like image 65
Petah Avatar answered Oct 07 '22 12:10

Petah


Firstly, the error message suggests you're tying to build a jdk.nashorn.internal.ir.ObjectNode, whereas I'm guessing you actually intended to build a com.fasterxml.jackson.databind.node.ObjectNode (for Jackson 2.x). Check your imports.

However, if all you want to do is build an empty ObjectNode, then just use

JsonNodeFactory.instance.objectNode()

If for some reason you really want to do it by parsing an empty JSON object, then use this:

ObjectNode json = (ObjectNode) new ObjectMapper().readTree("{}");

But that's just unpleasant.

like image 43
skaffman Avatar answered Oct 07 '22 12:10

skaffman