You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java Jackson:如何序列化不带引号的Double类型NaN值?

解决Jackson序列化Double.NaN为原生NaN而非字符串的问题

问题原因

你当前启用的ALLOW_NON_NUMERIC_NUMBERS是反序列化阶段的配置,仅用于允许Jackson解析JSON中的NaN/Infinity等非标准数值,对序列化行为没有影响。Jackson默认会将Double类型的NaN序列化为字符串"NaN"——因为严格JSON规范不包含NaN这类数值;若要输出原生的NaN,需开启序列化阶段的对应特性。

解决方案

在ObjectMapper中启用JsonGenerator.Feature.ALLOW_NON_NUMERIC_NUMBERS特性,该配置允许Jackson在序列化时输出NaN、Infinity等非标准数值。

修改后的代码如下:

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.json.JsonReadFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Test {
    public String name;
    public int age;
    private int favoriteNumber;
    private Double value = Double.NaN;

    public Test(String name, int age, int favoriteNumber) {
        this.name = name;
        this.age = age;
        this.favoriteNumber = favoriteNumber;
    }

    @JsonProperty
    public String getFavoriteNumber() {
        return String.valueOf(favoriteNumber);
    }

    @JsonProperty
    public Double getValue() {
        return this.value;
    }

    public static void main(String... args) throws Exception {
        Test p = new Test("Joe", 25, 123);
        ObjectMapper mapper = new ObjectMapper();
        // 核心配置:序列化时允许输出NaN等非标准数值
        mapper.configure(JsonGenerator.Feature.ALLOW_NON_NUMERIC_NUMBERS, true);
        // 若需同时支持反解析NaN,保留以下配置(可选)
        mapper.enable(JsonReadFeature.ALLOW_NON_NUMERIC_NUMBERS.mappedFeature());
        mapper.configure(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS, true);
        System.out.println(mapper.writeValueAsString(p));
        // 输出结果:{"name":"Joe","age":25,"favoriteNumber":"123","value":NaN}
    }
}

关键说明

  • JsonGenerator.Feature.ALLOW_NON_NUMERIC_NUMBERS:控制序列化阶段是否允许输出NaN、+Infinity、-Infinity这类不符合严格JSON规范的数值。启用后,Double.NaN会被序列化为原生的NaN而非字符串。
  • 若不需要支持反序列化NaN,可以移除JsonParser相关的配置,仅保留序列化配置即可。

内容的提问来源于stack exchange,提问作者Bằng Rikimaru

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 01:28:19