|
| 1 | +package org.baeldung.jsoncomponent; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.core.JsonGenerator; |
| 4 | +import com.fasterxml.jackson.core.JsonParser; |
| 5 | +import com.fasterxml.jackson.core.JsonProcessingException; |
| 6 | +import com.fasterxml.jackson.core.TreeNode; |
| 7 | +import com.fasterxml.jackson.databind.DeserializationContext; |
| 8 | +import com.fasterxml.jackson.databind.JsonDeserializer; |
| 9 | +import com.fasterxml.jackson.databind.JsonSerializer; |
| 10 | +import com.fasterxml.jackson.databind.SerializerProvider; |
| 11 | +import com.fasterxml.jackson.databind.node.TextNode; |
| 12 | +import javafx.scene.paint.Color; |
| 13 | +import org.springframework.boot.jackson.JsonComponent; |
| 14 | + |
| 15 | +import java.io.IOException; |
| 16 | + |
| 17 | +@JsonComponent |
| 18 | +public class UserCombinedSerializer { |
| 19 | + public static class UserJsonSerializer extends JsonSerializer<User> { |
| 20 | + |
| 21 | + @Override |
| 22 | + public void serialize(User user, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { |
| 23 | + jsonGenerator.writeStartObject(); |
| 24 | + jsonGenerator.writeStringField("favoriteColor", |
| 25 | + getColorAsWebColor(user.getFavoriteColor())); |
| 26 | + jsonGenerator.writeEndObject(); |
| 27 | + } |
| 28 | + |
| 29 | + private static String getColorAsWebColor(Color color) { |
| 30 | + int r = (int) Math.round(color.getRed() * 255.0); |
| 31 | + int g = (int) Math.round(color.getGreen() * 255.0); |
| 32 | + int b = (int) Math.round(color.getBlue() * 255.0); |
| 33 | + return String.format("#%02x%02x%02x", r, g, b); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + @JsonComponent |
| 38 | + public static class UserJsonDeserializer extends JsonDeserializer<User> { |
| 39 | + @Override |
| 40 | + public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { |
| 41 | + TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser); |
| 42 | + TextNode favoriteColor = (TextNode) treeNode.get("favoriteColor"); |
| 43 | + return new User(Color.web(favoriteColor.asText())); |
| 44 | + } |
| 45 | + } |
| 46 | +} |
0 commit comments