ViRALiC ViRALiC - 1 year ago 103
JSON Question

json string to Java object with Jackson

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
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 Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download