Search code examples
javajsonjackson

Convert JsonNode into POJO


This may seem a little unusual, but I am looking for an efficient way to transform/map a JsonNode into a POJO.

I store some of my Model's information in json files and I have to support a couple of version of my model.

What I do is load the json file in memory in a JsonNode, apply a couple of versioning strategies to make it match the latest version of my Model.

    ObjectMapper mapper = new ObjectMapper();
    BufferedReader fileReader = new BufferedReader(new FileReader(projPath));

    JsonNode rootNode = mapper.readTree(fileReader);

    //Upgrade our file in memory
    applyVersioningStrategy(rootNode);

    ProjectModel project = mapJsonNodeToProject(rootNode);

Unless there's a faster way to do it, I will probably end up simply manually applying the JsonNodes to my Model


Solution

  • In Jackson 2.4, you can convert as follows:

    MyClass newJsonNode = jsonObjectMapper.treeToValue(someJsonNode, MyClass.class);
    

    where jsonObjectMapper is a Jackson ObjectMapper.


    In older versions of Jackson, it would be

    MyClass newJsonNode = jsonObjectMapper.readValue(someJsonNode, MyClass.class);