views:

134

answers:

2

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 e.g. {"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

+1  A: 

You need to use an ObjectMapper as shown here:

ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getJsonFactory();
JsonParser jp = factory.createJsonParser("{\"k1\":\"v1\"}");
JsonNode actualObj = mapper.readTree(jp);
Richard Fearn
A: 

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

But usually you just use ObjectMapper and 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.

StaxMan