Question

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?

Was it helpful?

Solution

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);

OTHER TIPS

And instead of handling errors in every mapper.readValue(json,Class) you can write a helper class which has another Generic method.

and use

String jsonString = "{\"id\":100,\"firstName\":\"Adam\"}";
Student student = JSONUtils.convertToObject(jsonString,Student.class);

I'm returning nulland fancying printing trace & checking null later on. You can handle error cases on your own way.

public class JSONUtils {
    public static String convertToJSON(Object object)
    {
        ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        String json;
        try {
            json = ow.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return convertToJSON(e);
        }
        return json;
    }


    public static <T> T convertToObject(Class<T> clazz,String jsonString)
    {
        try {
        ObjectMapper mapper = new ObjectMapper();
        return (T)mapper.readValue(jsonString, clazz);
        }catch(Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top