281

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

2
  • 68
    #embarrasing -- nope. If simple things aren't simple, then the API designer has failed, not you. Commented Aug 15, 2014 at 17:05
  • 1
    @StaxMan's answer in code: JsonFactory factory = new MappingJsonFactory(); Commented May 8, 2020 at 6:55

7 Answers 7

440

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

ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree("{\"k1\":\"v1\"}");
Sign up to request clarification or add additional context in comments.

2 Comments

For anyone who needs an ObjectNode rather than a JsonNode use mapper.valueToTree("{\"k1\":\"v1\"}")
@MatthewHerbst In 2.5.1, this creates a new text node with the string "{\"k1\":\"v1\"}" rather than parsing it as JSON.
75

You need to use an 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.

2 Comments

Is it possible to take the JsonNode, modify it a bit, and then call mapper.readValue(node, class); and get out a class?
Yes. There's even an alias for that, mapper.treeToValue(). But readValue() also works.
37

A third variant:

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

3 Comments

What did passing in JsonNode.class actually get you here?
@David: Nothing, so slashnick's variant is obviously better if you just want a JsonNode. However, you usually don't want a JsonNode, so I wanted to show how to tell Jackson what kind of value of you want.
For me, passing JsonNode was apparently necessary to prevent Jackson from deserializing it as something else - which would have failed.
5

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

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

Comments

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

Comments

4

New approach to old question. A solution that works from java 9+

ObjectNode agencyNode = new ObjectMapper().valueToTree(Map.of("key", "value"));

is more readable and maintainable for complex objects. Ej

Map<String, Object> agencyMap = Map.of(
        "name", "Agencia Prueba",
        "phone1", "1198788373",
        "address", "Larrea 45 e/ calligaris y paris",
        "number", 267,
        "enable", true,
        "location", Map.of("id", 54),
        "responsible", Set.of(Map.of("id", 405)),
        "sellers", List.of(Map.of("id", 605))
);
ObjectNode agencyNode = new ObjectMapper().valueToTree(agencyMap);

Comments

0

In kotlin:

import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue

val data = ObjectMapper().readValue<JsonNode>("{\"field\":\"value\"}")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.