-
Notifications
You must be signed in to change notification settings - Fork 495
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[BUG] 序列化枚举类如果是负数会直接crash #2531
Comments
源码由于用到了数组,所以判断了 index 不能为负数 fastjson2/core/src/main/java/com/alibaba/fastjson2/reader/ObjectReaderImplEnum.java Lines 235 to 240 in c86bb80
你可以自定义枚举的反序列化,代码如下: ParserConfig.getGlobalInstance().putDeserializer(EnumClass.class, new ObjectDeserializer() {
@SuppressWarnings("unchecked")
@Override
public <T> T deserialze(final DefaultJSONParser parser, final Type type, final Object fieldName) {
Integer intValue = parser.parseObject(int.class);
if (intValue == -1) {
return (T) EnumClass.NEGATIVE_ONE;
}
return (T) Arrays.stream(EnumClass.values())
.filter(it -> it.getCode() == intValue)
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("No enum value: " + intValue));
}
}); |
https://oss.sonatype.org/content/repositories/snapshots/com/alibaba/fastjson/2.0.50-SNAPSHOT/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
问题描述
简要描述您碰到的问题。
在序列化枚举类时有负数的情况
环境信息
请填写以下信息:
重现步骤
Test case
期待的正确结果
能够正常序列化
相关日志输出
*com.alibaba.fastjson.JSONException: read field 'Test243$Mock.setCode, offset 11, character }, line 1, column 11, fastjson-version 2.0.49 {"code":-1}
Caused by: com.alibaba.fastjson2.JSONException: No enum ordinal Test243.EnumClass.-1
at com.alibaba.fastjson2.reader.ObjectReaderImplEnum.readObject(ObjectReaderImplEnum.java:238)
at com.alibaba.fastjson2.reader.FieldReaderObject.readFieldValue(FieldReaderObject.java:154)
at com.alibaba.fastjson2.reader.ObjectReader1.readObject(ObjectReader1.java:286)
at com.alibaba.fastjson.JSON.parseObject(JSON.java:543)
... 26 more。*
The text was updated successfully, but these errors were encountered: