JSON string to Java object with Jackson

ViRALiC picture ViRALiC · Feb 8, 2014 · Viewed 17.7k times · Source

This is probably one of those questions where the title says it all.

I am quite fascinated by the ObjectMapper's readValue(file, class) method, found within the Jackson library which reads a JSON string from a file and assigns it to an object.

I'm curious if this is possible to do by simply getting JSON from a string and applying it to an object.

Some sort of alternative readValue() method, which takes a String, instead of a file, and assigns it to an object?

For instance, while the default readValue(file, class) method looks like this:

ObjectMapper mapper = new ObjectMapper();
Student student = mapper.readValue("C:\\student.json", Student.class);

I was wondering if there was some method in Jackson, which allowed the following:

ObjectMapper mapper = new ObjectMapper();
Student student = mapper.readValue("{\"id\":100,\"firstName\":\"Adam\"}", Student.class);

The second example takes a string and an object of a class while the first one takes a file and an object of a class.

I just want to cut out the middle man, in this case, the file.

Is this doable or does no such method exist within the constraints of Jackson?

Answer

Dan Ciborowski - MSFT picture Dan Ciborowski - MSFT · Feb 8, 2014

Try this,

You can't create a new string like your doing.

    String string = "{\"id\":100,\"firstName\":\"Adam\"}";
    Student student = mapper.readValue(string, Student.class);