BAEL-6311: Applying @JsonValue on fields in Jackson (#13749)

Co-authored-by: Luis Javier Peris Morillo <javierperis@gmail.com>
This commit is contained in:
Azhwani 2023-04-09 10:26:01 +02:00 committed by GitHub
parent 44b59b1ace
commit b280691134
2 changed files with 24 additions and 2 deletions

View File

@ -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;
}
}

View File

@ -25,6 +25,7 @@ import com.baeldung.jackson.annotation.ignore.MyMixInForIgnoreType;
import com.baeldung.jackson.annotation.dtos.withEnum.DistanceEnumWithValue; import com.baeldung.jackson.annotation.dtos.withEnum.DistanceEnumWithValue;
import com.baeldung.jackson.annotation.exception.UserWithRoot; import com.baeldung.jackson.annotation.exception.UserWithRoot;
import com.baeldung.jackson.annotation.exception.UserWithRootNamespace; 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.Item;
import com.baeldung.jackson.annotation.jsonview.Views; import com.baeldung.jackson.annotation.jsonview.Views;
import com.fasterxml.jackson.core.JsonProcessingException; 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 @Test
public void whenSerializingUsingJsonSerialize_thenCorrect() throws JsonProcessingException, ParseException { public void whenSerializingUsingJsonSerialize_thenCorrect() throws JsonProcessingException, ParseException {
final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
@ -433,6 +441,4 @@ public class JacksonAnnotationUnitTest {
} }
} }