13

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?

anothernode
  • 5,100
  • 13
  • 43
  • 62
ViRALiC
  • 1,419
  • 4
  • 18
  • 46
  • 2
    Please read the [javadoc](http://fasterxml.github.io/jackson-databind/javadoc/2.1.0/com/fasterxml/jackson/databind/ObjectMapper.html#readValue(java.lang.String,java.lang.Class))... – Sotirios Delimanolis Feb 08 '14 at 00:41
  • Show your Student Class. – jeremyjjbrown Feb 08 '14 at 00:42
  • 1
    [`ObjectMapper#readValue(String, Class)` exists.](http://fasterxml.github.io/jackson-databind/javadoc/2.3.0/com/fasterxml/jackson/databind/ObjectMapper.html#readValue%28java.lang.String,%20java.lang.Class%29) Did you miss it? – Matt Ball Feb 08 '14 at 00:45
  • @MattBall Oh my God, it does. I'm such an idiot. Thank you never the less, friend. – ViRALiC Feb 08 '14 at 00:47

2 Answers2

19

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);
Dan Ciborowski - MSFT
  • 6,807
  • 10
  • 53
  • 88
  • 1
    Constructing an ObjectMapper is relatively expensive; I can't recommend doing it every time a method is called. – Matt Ball Feb 08 '14 at 00:42
  • Yea, I got ride of that when I saw the reason why it was failing is OP didn't but his string in "" – Dan Ciborowski - MSFT Feb 08 '14 at 00:48
  • 1
    I'm a complete idiot, and I feel embarrassed to have asked this question. Thank you both for helping clear up my retardation. – ViRALiC Feb 08 '14 at 00:50
  • Thank you @djc391, I will. Thank you both for not making me feel too horrid about such a dumb question. – ViRALiC Feb 08 '14 at 00:55
  • I have a json which has inner Arrays and inner Arrays. Consider each array has an object. In this case how to map json with inner Arrays to POJO java objects. – Ravi May 18 '22 at 08:46
4

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;
        }
    }
}
Davut Gürbüz
  • 5,526
  • 4
  • 47
  • 83