I have a JSON file that contains an array within it. I'm able to read the data fine but unsure of how I would print the array values out. Below I'm manually selecting the 3rd car. I need to show all cars. Not all persons have the same number of cars available. Some have 1 some have 3.... I keep running into null error when I try different kinds of loops.
Thanks!
try {
ObjectMapper mapper = new ObjectMapper();
InputStream inputStream = new FileInputStream(new File("/Users/blah/Downloads/persons.json"));
TypeReference<List<Person>> typeReference = new TypeReference<List<Person>>() {};
List<Person> persons = mapper.readValue(inputStream, typeReference);
for (Person p : persons) {
System.out.printf("name is %s city is %s cars available %s%n",
p.getFirstName(),
p.getAddress().getCity(),
p.getCars()[2]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
JSON Example:
[
{
"firstName": "Leanne Graham",
"lastName": "Bret",
"age": 25,
"address": {
"street": "123 Main St",
"city": "Bellevue",
"zip": "90007"
},
"cars": [
"Toyota Corolla",
"Honda Civic",
]
},
{
"firstName": "Steve Graham",
"lastName": "Bret",
"age": 25,
"address": {
"street": "123 Main St",
"city": "Bellevue",
"zip": "90007"
},
"cars": [
"Toyota Corolla",
"Honda Civic",
"Infiniti G35"
]
},
{
"firstName": "Sally Graham",
"lastName": "Bret",
"age": 25,
"address": {
"street": "123 Main St",
"city": "Bellevue",
"zip": "90007"
},
"cars": [
"Toyota Corolla",
"Honda Civic",
"Infiniti G35"
]
}
]