Skip to content

Commit

Permalink
fix writeDouble and writeFloat of JSONWriter when value Not a Number …
Browse files Browse the repository at this point in the history
…, for issue #1562
  • Loading branch information
yanxutao89 authored and wenshao committed Jun 14, 2023
1 parent 688579d commit 8876c08
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
8 changes: 8 additions & 0 deletions core/src/main/java/com/alibaba/fastjson2/JSONWriter.java
Original file line number Diff line number Diff line change
Expand Up @@ -876,6 +876,10 @@ public final void writeFloat(float value, DecimalFormat format) {
writeFloat(value);
return;
}
if (Float.isNaN(value) || Float.isInfinite(value)) {
writeNull();
return;
}

String str = format.format(value);
writeRaw(str);
Expand Down Expand Up @@ -933,6 +937,10 @@ public final void writeDouble(double value, DecimalFormat format) {
writeDouble(value);
return;
}
if (Double.isNaN(value) || Double.isInfinite(value)) {
writeNull();
return;
}

String str = format.format(value);
writeRaw(str);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.alibaba.fastjson2.issues_1500;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.annotation.JSONField;
import lombok.Data;
import org.junit.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class Issue1562 {
@Test
public void test() {
String expected = "{\"value\":null,\"value10\":null,\"value11\":null,\"value12\":null,\"value2\":null,\"value3\":null,\"value4\":null,\"value5\":null,\"value6\":null,\"value7\":null,\"value8\":null,\"value9\":null}";
assertEquals(expected, JSON.toJSONString(new Cs()));
}

@Data
class Cs {
@JSONField(format = "#.##")
private double value = Double.NaN;
@JSONField(format = "#.##")
private float value2 = Float.NaN;
@JSONField(format = "#.##")
private double value3 = Double.NEGATIVE_INFINITY;
@JSONField(format = "#.##")
private float value4 = Float.NEGATIVE_INFINITY;
@JSONField(format = "#.##")
private double value5 = Double.POSITIVE_INFINITY;
@JSONField(format = "#.##")
private float value6 = Float.POSITIVE_INFINITY;
@JSONField
private double value7 = Double.NaN;
@JSONField
private float value8 = Float.NaN;
@JSONField
private double value9 = Double.NEGATIVE_INFINITY;
@JSONField
private float value10 = Float.NEGATIVE_INFINITY;
@JSONField
private double value11 = Double.POSITIVE_INFINITY;
@JSONField
private float value12 = Float.POSITIVE_INFINITY;
}
}

0 comments on commit 8876c08

Please sign in to comment.