Search code examples
javajacksonescapingnan

Java Jackson - How to serialize Double NaN without quote?


I need to serialize a Double field containing NaN number, but Jackson always tries to write it as a String, e.g. "value": "Nan". How can I change it to "value": Nan instead?

Below is the code to reproduce:

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"}
    }
}

Solution

  • Add the annotation @JsonRawValue, like this

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

    It will give you this result {"name":"Joe","age":25,"favoriteNumber":"123","value":NaN}