alibaba / alibaba/fastjson2

[BUG]关于JSONObject.parseObject()反序列化整形数据的bug

Open
#3,261 1 comment 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

### 问题描述
*简要描述您碰到的问题。*
当我对一个json格式的字符串{"a":"-"}反序列化为long或int整形类型时,会成功。但是转为double或float类型时却失败了。

### 环境信息
*请填写以下信息:*
- JDK信息: [e.g.:Openjdk 1.8.0_291]
- 版本信息:[e.g.:Fastjson2 2.0.19]

### 重现步骤
*如何操作可以重现该问题:*

1. 使用 `JSONObject.parseObject(json, Test.class)` 方法
2. 当a为int或long类型则不会报错,结果为0.当a是float或者double类型则报错“For input string: "-"”
```java
@Data
public class Test {

private float a;
// private int a;

public static void main(String[] args) {
String json = "{\"a\":\"-\"}";
Test test = JSONObject.parseObject(json, Test.class);
System.out.println(test);
}
}

### 期待的正确结果
既然是字符串转数字要么都会失败,要么都转为默认值。

### 相关日志输出
失败:
Exception in thread "main" java.lang.NumberFormatException: For input string: "-"
at com.alibaba.fastjson2.FloatingDecimal.parseFloat(FloatingDecimal.java:649)
at com.alibaba.fastjson2.JSONReaderUTF16.readFloatValue(JSONReaderUTF16.java:3293)
at com.alibaba.fastjson2.reader.FieldReaderFloatValueMethod.readFieldValue(FieldReaderFloatValueMethod.java:20)
at com.alibaba.fastjson2.reader.ObjectReader1.readObject(ObjectReader1.java:276)
at com.alibaba.fastjson2.JSON.parseObject(JSON.java:600)
at com.alibaba.fastjson2.JSONObject.parseObject(JSONObject.java:1835)
at com.gd.fileTransfer.bo.Test.main(Test.java:12)
成功:
Test(a=0)

#### 附加信息
*如果你还有其他需要提供的信息,可以在这里填写(可以提供截图、视频等)。*

Contributor guide

Open the contributing guide

Research direction

Start by reproducing the JSONObject.parseObject(json, Test.class) example with float, double, int, and long fields, then inspect the stack-trace entry points JSONReaderUTF16.readFloatValue and the corresponding numeric readers. Done means the handling of the string "-" is consistent across these numeric types and the behavior is covered by a regression test.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
backend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.