我需要序列化包含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"}
}
}
2条答案
按热度按时间vqlkdk9b1#
这是不可能的,因为
NaN
不是有效的JSON值。您可以尝试在getter方法中将其转换为null。wmomyfyw2#
添加注解
@JsonRawValue
,如下所示它会给予你这个结果
{"name":"Joe","age":25,"favoriteNumber":"123","value":NaN}