Display Name Display Name - 4 months ago 29
Java Question

ObjectMapper - JSON file to Object

I'm trying to learn to code JAVA. I have a .json file in my resources folder. I would like to parse it into an Object with ObjectMapper. A searched the whole network for a simple solution that works for me, but find nothing.
Thank You!

Answer

The easiest way is to have a class who's member variables share names with the keys in your JSON file.

public class Person {

    private String name;
    private int age;
    ... add getters and setters
}

if your JSON file was :

{
   "name":"Josh",
   "age":36
}

ObjectMapper mapper =  new ObjectMapper();
Person p = mapper.readValue(new File("filename"), Person.class);