JavaJackson-如何不带引号序列化Double NaN?

vnzz0bqm  于 12个月前  发布在  Java
关注(0)|答案(2)|浏览(143)

我需要序列化包含NaN数字的Double字段,但Jackson总是试图将其写成String,例如。"value": "Nan",怎么改成"value": Nan
下面是复制的代码:

import com.fasterxml.jackson.annotation.JsonProperty;
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();
        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"}
    }
}
vqlkdk9b

vqlkdk9b1#

这是不可能的,因为NaN不是有效的JSON值。您可以尝试在getter方法中将其转换为null。

wmomyfyw

wmomyfyw2#

添加注解@JsonRawValue,如下所示

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

它会给予你这个结果{"name":"Joe","age":25,"favoriteNumber":"123","value":NaN}

相关问题