Home > AI > Backend > SpringBoot > Jackson >

ObjectMapper

Step 1: include the dependency

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.12.3</version>
</dependency>

Step 2: Example Code:

ObjectMapper objectMapper = new ObjectMapper();

// Object to JSON string
Car car = new Car("yellow", "renault");
objectMapper.writeValue(new File("target/car.json"), car);
String carAsString = objectMapper.writeValueAsString(car);
System.out.println(carAsString);

// JSON string to Object
String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
Car car2 = objectMapper.readValue(json, Car.class);
System.out.println(car2);

// JSON file to Object
Car car3 = objectMapper.readValue(new File("target/car.json"), Car.class);
Car car4 = objectMapper.readValue(new URL("file:target/car.json"), Car.class);
System.out.println(car3);
System.out.println(car4);

// JSON string to JSON node
JsonNode jsonNode = objectMapper.readTree(json);
String color = jsonNode.get("color").asText();
System.out.println(color);

// JSON string to list of Object
String jsonCarArray = "[{ \"color\" : \"Black\", \"type\" : \"BMW\" }, { \"color\" : \"Red\", \"type\" : \"FIAT\" }]";
List<Car> listCar = objectMapper.readValue(jsonCarArray, new TypeReference<List<Car>>(){});
Related posts:

Leave a Reply