Search code examples
javajsonparsingjacksonfasterxml

Accessing JSON values when parsing


I have a file called persons.json:

[
  {
    "id": 1,
    "name": "The Best",
    "email": "thenextbigthing@gmail.com",
    "birthDate": "1981-11-23"
  },
  {
    "id": 2,
    "name": "Andy Jr.",
    "email": "usa@gmail.com",
    "birthDate": "1982-12-01"
  },
  {
    "id": 3,
    "name": "JohnDoe",
    "email": "gameover@gmail.com",
    "birthDate": "1990-01-02"
  },
  {
    "id": 4,
    "name": "SomeOne",
    "email": "rucksack@gmail.com",
    "birthDate": "1988-01-22"
  },
  {
    "id": 5,
    "name": "Mr. Mxyzptlk",
    "email": "bigman@hotmail.com",
    "birthDate": "1977-08-12"
  }
]

I'd like to parse this file into an ArrayList with FasterXML, possibly with it's ObjectMapper() function and then being able to access each value (id, name, etc.) individually as a String when iterating through the newly created ArrayList. How could I do that? I don't even know what kind of list I could/should use in order to get access to each value individually. I'm kind of stuck here. List<???>


Solution

  • First of all:

    FasterXML uses Jackson underneath to parse/produce json.

    Now: to use Jackson, first of all create a container object for the data of your json, which we will call Person

    public class Person {
      private int id;
      private String name, email;
      @JsonFormat
      (shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
      private Date birthDate;
    
      //add here getters and setters ...
    }
    

    At this point, supposing you have pathToPersonsJsonFile as a string containing the path to your persons.json, you can use your file like this:

    byte[] jsonData = Files.readAllBytes(Paths.get(pathToPersonsJsonFile));
    ObjectMapper objectMapper = new ObjectMapper();
    Person[] parsedAsArray = objectMapper.readValue(jsonData, Person[].class); //array
    ArrayList<Persons> persons = new ArrayList<>(Arrays.asList(parsedAsArray)); //your list
    

    Note: JsonFormat enables to declare which format that value has on your json.