java jsonparser stream objectmapper code example

Example 1: how to read file in java jacakson

try {
    // create object mapper instance
    ObjectMapper mapper = new ObjectMapper();

    // convert JSON file to map
    Map<?, ?> map = mapper.readValue(Paths.get("book.json").toFile(), Map.class);

    // print map entries
    for (Map.Entry<?, ?> entry : map.entrySet()) {
        System.out.println(entry.getKey() + "=" + entry.getValue());
    }

} catch (Exception ex) {
    ex.printStackTrace();
}

Example 2: convert json to object jackson

ObjectMapper objectMapper = new ObjectMapper();

String carJson =
    "{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";

try {
    Car car = objectMapper.readValue(carJson, Car.class);

    System.out.println("car brand = " + car.getBrand());
    System.out.println("car doors = " + car.getDoors());
} catch (IOException e) {
    e.printStackTrace();
}

Tags:

Java Example