alibaba / alibaba/fastjson2

[BUG] fastjson2.0.65版本使用JSONB报错,Cannot invoke "java.lang.Enum.ordinal()" because "e" is null

Open Beginner friendly
#7,862 0 comments 0 reactions 0 assignees View on GitHub
bug
Dominant language
Java
Stars
4.4k
Forks
613
Avg merge
1d 22h
Merged PRs (30d)
6

Description

### 问题描述
fastjson 2.0.65版本,使用JSONB序列化报错。
异常堆栈信息:
```
Caused by: java.lang.NullPointerException: Cannot invoke "java.lang.Enum.ordinal()" because "e" is null
at com.alibaba.fastjson2.JSONB$IO.writeEnum(JSONB.java:2196) ~[fastjson2-2.0.65.jar:?]
at com.alibaba.fastjson2.writer.OWG_10_5_ResultValue.writeJSONB(Unknown Source) ~[?:?]
at com.alibaba.fastjson2.JSONB.toBytes(JSONB.java:1836) ~[fastjson2-2.0.65.jar:?]
at com.yuanian.infrastructure.cache.service.EpochFastJson2WithZipRedisSerializer.serialize(EpochFastJson2WithZipRedisSerializer.java:39) ~[com.yuanian.infrastructure.cache-ECS2.2.20260730.01.02.jar:?]
```
EpochFastJson2WithZipRedisSerializer.java:39行的代码信息:
```
byte[] bytes = JSONB.toBytes(t, JSONWriter.Feature.WriteClassName);
```

本人临时解决办法:
JSONB.java文件2190行左右修改后的内容:

```
/**
* Writes an enum value to a byte array
*
* @param bytes the byte array to write to
* @param off the offset in the byte array
* @param e the enum value to write
* @param features the features to apply
* @return the new offset
*/
static int writeEnum(byte[] bytes, int off, Enum e, long features) {
if (e == null) {
// JSONB null
bytes[off] = BC_NULL;
return off + 1;
}
if ((features & (MASK_WRITE_ENUM_USING_TO_STRING | MASK_WRITE_ENUMS_USING_NAME)) != 0) {
return writeString(bytes, off,
(features & WriteEnumUsingToString.mask) != 0
? e.toString()
: e.name()
);
} else {
return JSONB.IO.writeInt32(bytes, off, e.ordinal());
}
}
```
所增加的代码
```
if (e == null) {
// JSONB null
bytes[off] = BC_NULL;
return off + 1;
}
```

### 环境信息
*请填写以下信息:*

- OS信息: [windows10 & CentOS 7]
- JDK信息: [Openjdk 17]
- 版本信息:[Fastjson2 2.0.65]

### 问题总结
本人水平有限,如上解决方案不确定是否会导致其它问题,望官方知悉bug并解决。

Contributor guide

Open the contributing guide

Research direction

Start in JSONB.java around the writeEnum method at the line reported in the stack trace, and reproduce the failure through JSONB.toBytes(t, JSONWriter.Feature.WriteClassName). Check the behavior when the enum value is null and verify that JSONB serialization completes without the reported NullPointerException, including a regression test if the project’s existing tests cover this path.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
backend
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Active
Clarity
Clearly specified
Newbie friendliness
78/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.