Skip to content

Commit

Permalink
Improve Enum handling parity with Jackson (#818)
Browse files Browse the repository at this point in the history
  • Loading branch information
oujesky authored Apr 22, 2024
1 parent 6785905 commit bd82565
Show file tree
Hide file tree
Showing 7 changed files with 709 additions and 20 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -864,4 +864,41 @@ record Test(
URL | 'ws://junk'
}
void "test @JsonProperty on enum constant"() {
given:
def context = buildContext('test.Test', """
package test;

import com.fasterxml.jackson.annotation.JsonProperty;
import io.micronaut.serde.annotation.Serdeable;

@Serdeable
enum Test {
@JsonProperty("value_1") VALUE1,
@JsonProperty("value_2") VALUE2,
VALUE_WITHOUT_ANNOTATION
}
""")
when:
def enumConstant = context.classLoader.loadClass('test.Test')[constant]
def result = writeJson(jsonMapper, enumConstant)
then:
result == "\"$serialized\""
when:
def deserialized = jsonMapper.readValue(result, argumentOf(context, 'test.Test'))
then:
deserialized == enumConstant
cleanup:
context.close()
where:
constant | serialized
'VALUE1' | 'value_1'
'VALUE2' | 'value_2'
'VALUE_WITHOUT_ANNOTATION' | 'VALUE_WITHOUT_ANNOTATION'
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ class Foo {
@Serdeable
enum MyEnum {
VALUE1("value1"),
VALUE2("value2"),
VALUE3("value3");
VALUE1("value_1"),
VALUE2("value_2"),
VALUE3("value_3");
private final String value;
Expand All @@ -52,16 +52,21 @@ enum MyEnum {
when:
String json = jsonMapper.writeValueAsString(testBean)
then:
'{"myEnum":"value2"}' == json
'{"myEnum":"value_2"}' == json

when:
def foo = jsonMapper.readValue(json, testBean.class)

then:
foo.myEnum == enumValue2

when:
jsonMapper.readValue('{"myEnum":"invalid"}', testBean.class)
then:
thrown IOException
}

void "@JsonValue on field"() throws IOException {
void "enum @JsonValue on field"() throws IOException {
given:
def context = buildContext('''
package example;
Expand All @@ -82,9 +87,9 @@ class Foo {
}
@Serdeable
enum MyEnum {
VALUE1("value1"),
VALUE2("value2"),
VALUE3("value3");
VALUE1("value_1"),
VALUE2("value_2"),
VALUE3("value_3");
@JsonValue
private final String value;
MyEnum(String value) {
Expand All @@ -100,13 +105,18 @@ enum MyEnum {
when:
String json = jsonMapper.writeValueAsString(testBean)
then:
'{"myEnum":"value2"}' == json
'{"myEnum":"value_2"}' == json

when:
def foo = jsonMapper.readValue(json, testBean.class)

then:
foo.myEnum == enumValue2

when:
jsonMapper.readValue('{"myEnum":"invalid"}', testBean.class)
then:
thrown IOException
}

void "@JsonValue on constructor"() throws IOException {
Expand Down
Loading

0 comments on commit bd82565

Please sign in to comment.