From b280691134e3e77075b9031e9e3595757af58999 Mon Sep 17 00:00:00 2001 From: Azhwani <13301425+azhwani@users.noreply.github.com> Date: Sun, 9 Apr 2023 10:26:01 +0200 Subject: [PATCH] BAEL-6311: Applying @JsonValue on fields in Jackson (#13749) Co-authored-by: Luis Javier Peris Morillo --- .../jackson/annotation/PriorityEnum.java | 16 ++++++++++++++++ .../annotation/JacksonAnnotationUnitTest.java | 10 ++++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) create mode 100644 jackson-simple/src/main/java/com/baeldung/jackson/annotation/PriorityEnum.java diff --git a/jackson-simple/src/main/java/com/baeldung/jackson/annotation/PriorityEnum.java b/jackson-simple/src/main/java/com/baeldung/jackson/annotation/PriorityEnum.java new file mode 100644 index 0000000000..ed74052ede --- /dev/null +++ b/jackson-simple/src/main/java/com/baeldung/jackson/annotation/PriorityEnum.java @@ -0,0 +1,16 @@ +package com.baeldung.jackson.annotation; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum PriorityEnum { + + LOW(0), MEDIUM(1), HIGH(3); + + @JsonValue + private int level; + + PriorityEnum(int level) { + this.level = level; + } + +} diff --git a/jackson-simple/src/test/java/com/baeldung/jackson/annotation/JacksonAnnotationUnitTest.java b/jackson-simple/src/test/java/com/baeldung/jackson/annotation/JacksonAnnotationUnitTest.java index 9fb982842f..57ef231825 100644 --- a/jackson-simple/src/test/java/com/baeldung/jackson/annotation/JacksonAnnotationUnitTest.java +++ b/jackson-simple/src/test/java/com/baeldung/jackson/annotation/JacksonAnnotationUnitTest.java @@ -25,6 +25,7 @@ import com.baeldung.jackson.annotation.ignore.MyMixInForIgnoreType; import com.baeldung.jackson.annotation.dtos.withEnum.DistanceEnumWithValue; import com.baeldung.jackson.annotation.exception.UserWithRoot; import com.baeldung.jackson.annotation.exception.UserWithRootNamespace; +import com.baeldung.jackson.annotation.ignore.MyMixInForIgnoreType; import com.baeldung.jackson.annotation.jsonview.Item; import com.baeldung.jackson.annotation.jsonview.Views; import com.fasterxml.jackson.core.JsonProcessingException; @@ -97,6 +98,13 @@ public class JacksonAnnotationUnitTest { } + @Test + public void whenSerializingFieldUsingJsonValue_thenCorrect() throws IOException { + final String enumAsString = new ObjectMapper().writeValueAsString(PriorityEnum.HIGH); + + assertEquals("3", enumAsString); + } + @Test public void whenSerializingUsingJsonSerialize_thenCorrect() throws JsonProcessingException, ParseException { final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); @@ -432,7 +440,5 @@ public class JacksonAnnotationUnitTest { */ } - - }