Skip to content

Commit

Permalink
improved jdk8 optional support
Browse files Browse the repository at this point in the history
  • Loading branch information
wenshao committed Mar 23, 2021
1 parent 3ec5aab commit 732c2a3
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -676,7 +676,8 @@ public <T> T parseObject(Type type, Object fieldName) {
int token = lexer.token();
if (token == JSONToken.NULL) {
lexer.nextToken();
return null;

return (T) TypeUtils.optionalEmpty(type);
}

if (token == JSONToken.LITERAL_STRING) {
Expand Down
28 changes: 28 additions & 0 deletions src/main/java/com/alibaba/fastjson/util/TypeUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -3327,4 +3327,32 @@ public static boolean isJacksonCreator(Method method) {
}
return class_JacksonCreator != null && method.isAnnotationPresent(class_JacksonCreator);
}

private static Object OPTIONAL_EMPTY;
private static boolean OPTIONAL_ERROR = false;
public static Object optionalEmpty(Type type) {
if (OPTIONAL_ERROR) {
return null;
}

Class clazz = getClass(type);
if (clazz == null) {
return null;
}

String className = clazz.getName();

if ("java.util.Optional".equals(className)) {
if (OPTIONAL_EMPTY == null) {
try {
Method empty = Class.forName(className).getMethod("empty");
OPTIONAL_EMPTY = empty.invoke(null);
} catch (Throwable e) {
OPTIONAL_ERROR = true;
}
}
return OPTIONAL_EMPTY;
}
return null;
}
}
10 changes: 10 additions & 0 deletions src/test/java/com/alibaba/json/bvt/jdk8/OptionalTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -74,4 +74,14 @@ public void test_optionalDouble() throws Exception {
OptionalDouble val2 = JSON.parseObject(text, OptionalDouble.class);
Assert.assertEquals(Double.toString(val.getAsDouble()), Double.toString(val2.getAsDouble()));
}

public void test_optional_parseNull() throws Exception {
assertSame(Optional.empty()
, JSON.parseObject("null", Optional.class));
}

public void test_optional_parseNull_2() throws Exception {
assertSame(Optional.empty()
, JSON.parseObject("null", new TypeReference<Optional<Integer>>() {}));
}
}

0 comments on commit 732c2a3

Please sign in to comment.