How to parse a JSON string into JsonNode in Jackson?

322,592

Solution 1

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\"}");

Solution 2

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.

Solution 3

A third variant:

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

Solution 4

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.

Solution 5

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

Related videos on Youtube

fadmaa
Author by

fadmaa

Updated on January 02, 2021

Comments

  • fadmaa
    fadmaa over 3 years

    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

    • jameshfisher
      jameshfisher over 9 years
      #embarrasing -- nope. If simple things aren't simple, then the API designer has failed, not you.
    • Juan Rojas
      Juan Rojas
      @StaxMan's answer in code: JsonFactory factory = new MappingJsonFactory();
  • Matthew Herbst
    Matthew Herbst about 9 years
    For anyone who needs an ObjectNode rather than a JsonNode use mapper.valueToTree("{\"k1\":\"v1\"}")
  • minexew
    minexew about 8 years
    @MatthewHerbst In 2.5.1, this creates a new text node with the string "{\"k1\":\"v1\"}" rather than parsing it as JSON.