Skip to content

Commit 6e4c06a

Browse files
committed
jsonfield defaultValue support enum, for issue #2239
1 parent 44d36cf commit 6e4c06a

File tree

3 files changed

+32
-2
lines changed

3 files changed

+32
-2
lines changed

core/src/main/java/com/alibaba/fastjson2/reader/FieldReaderObject.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -125,8 +125,10 @@ public void readFieldValue(JSONReader jsonReader, T object) {
125125

126126
Object value;
127127
try {
128-
if (jsonReader.nextIfNull()) {
129-
if (fieldClass == OptionalInt.class) {
128+
if (jsonReader.nextIfNullOrEmptyString()) {
129+
if (defaultValue != null) {
130+
value = defaultValue;
131+
} else if (fieldClass == OptionalInt.class) {
130132
value = OptionalInt.empty();
131133
} else if (fieldClass == OptionalLong.class) {
132134
value = OptionalLong.empty();

core/src/main/java/com/alibaba/fastjson2/reader/ObjectReaderCreator.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2524,6 +2524,9 @@ public <T> FieldReader<T> createFieldReader(
25242524
Field field,
25252525
ObjectReader initReader
25262526
) {
2527+
if (defaultValue instanceof String && fieldClass.isEnum()) {
2528+
defaultValue = Enum.valueOf(fieldClass, (String) defaultValue);
2529+
}
25272530
if (defaultValue != null && defaultValue.getClass() != fieldClass) {
25282531
ObjectReaderProvider provider = JSONFactory
25292532
.getDefaultObjectReaderProvider();
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.alibaba.fastjson2.issues_2200;
2+
3+
import com.alibaba.fastjson2.JSON;
4+
import com.alibaba.fastjson2.annotation.JSONField;
5+
import org.junit.jupiter.api.Test;
6+
7+
import static org.junit.jupiter.api.Assertions.assertEquals;
8+
9+
public class Issue2239 {
10+
@Test
11+
public void test() {
12+
assertEquals(Type.NONE, JSON.parseObject("{}", Bean.class).type);
13+
assertEquals(Type.NONE, JSON.parseObject("{\"type\":null}", Bean.class).type);
14+
assertEquals(Type.NONE, JSON.parseObject("{\"type\":\"\"}", Bean.class).type);
15+
}
16+
17+
public static class Bean {
18+
@JSONField(defaultValue = "NONE")
19+
public Type type;
20+
}
21+
22+
public enum Type {
23+
NONE, ONE, TWO
24+
}
25+
}

0 commit comments

Comments
 (0)