Tim
Tim

Reputation: 583

Java reading json with Jackson - embedded array

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"
    ]
  }
]

Upvotes: 0

Views: 106

Answers (2)

bkis
bkis

Reputation: 2587

You can use Arrays.toString(p.getCars()) for that.
BTW you should implement (override) the toString() method in your Person class. toString() is meant to give a meaningful string representation of an object. If you have done so, you can just go

for (Person p : persons) System.out.println(p);

Upvotes: 1

azro
azro

Reputation: 54148

You should implement that in the toString of the Person class, and to print the whole array use Arrays.toString()

public class Person{        
    public String toString(){         
        return String.format("name is %s city is %s cars available %s", p.getFirstName(),
                             p.getAddress().getCity(), Arrays.toString(p.getCars()));
    }
}

And use

for (Person p : persons) {
    System.out.println(p);
}

Upvotes: 1

Related Questions