How to parse a JSON string into JsonNode in Jackson?

fadmaa picture fadmaa · Sep 6, 2010 · Viewed 292.7k times · Source

It should be so simple, but I just cannot find it after being trying for an hour #embarrasing.

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

Answer

slashnick picture slashnick · Mar 7, 2012

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