|
| 1 | +package com.baeldung.jackson.objectmapper; |
| 2 | + |
| 3 | +import org.slf4j.Logger; |
| 4 | +import org.slf4j.LoggerFactory; |
| 5 | + |
| 6 | +import com.baeldung.jackson.objectmapper.dto.Car; |
| 7 | +import com.fasterxml.jackson.core.Version; |
| 8 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 9 | +import com.fasterxml.jackson.databind.module.SimpleModule; |
| 10 | + |
| 11 | +public class JsonAdvancedCustomSerializeExample extends Example |
| 12 | +{ |
| 13 | + |
| 14 | + protected final Logger Logger = LoggerFactory.getLogger(getClass()); |
| 15 | + |
| 16 | + public JsonAdvancedCustomSerializeExample() { } |
| 17 | + |
| 18 | + String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }"; |
| 19 | + |
| 20 | + @Override |
| 21 | + public String name() |
| 22 | + { |
| 23 | + return this.getClass().getName(); |
| 24 | + } |
| 25 | + |
| 26 | + @Override |
| 27 | + public void execute() |
| 28 | + { |
| 29 | + Logger.debug("Executing: "+name()); |
| 30 | + try |
| 31 | + { |
| 32 | + ObjectMapper mapper = new ObjectMapper(); |
| 33 | + final SimpleModule module = new SimpleModule("CustomSerializer", new Version(1, 0, 0, null, null, null)); |
| 34 | + module.addSerializer(Car.class, new CustomCarSerializer()); |
| 35 | + mapper = new ObjectMapper(); |
| 36 | + mapper.registerModule(module); |
| 37 | + final Car car = new Car("yellow", "renault"); |
| 38 | + final String carJson = mapper.writeValueAsString(car); |
| 39 | + Logger.debug("car as json = " + carJson); |
| 40 | + } |
| 41 | + catch (final Exception e) |
| 42 | + { |
| 43 | + Logger.error(e.toString()); |
| 44 | + } |
| 45 | + try |
| 46 | + { |
| 47 | + ObjectMapper mapper = new ObjectMapper(); |
| 48 | + final SimpleModule module = new SimpleModule("CustomCarDeserializer", new Version(1, 0, 0, null, null, null)); |
| 49 | + module.addDeserializer(Car.class, new CustomCarDeserializer()); |
| 50 | + mapper = new ObjectMapper(); |
| 51 | + mapper.registerModule(module); |
| 52 | + final Car car = mapper.readValue(json, Car.class); |
| 53 | + Logger.debug("car type = " + car.getType()); |
| 54 | + Logger.debug("car color = " + car.getColor()); |
| 55 | + } |
| 56 | + catch (final Exception e) |
| 57 | + { |
| 58 | + Logger.error(e.toString()); |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments