当尝试将double值映射/设置为0.0时,ObjectMapper会将其视为等于null,从而在进行相等性比较时排除在外。
我有以下测试用例:
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;
import lombok.Getter;
import lombok.Setter;
import net.javacrumbs.jsonunit.JsonAssert;
import org.junit.Test;
public class ValidJson {
@Getter
@Setter
static class Temp {
Double dblValue;
Integer intVal;
boolean valid = false;
}
@Test
public void validJson() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(Include.NON_NULL);
objectMapper.setSerializationInclusion(Include.NON_DEFAULT);
String json = "{\"dblValue\":0.0}";
Temp generatedObj = objectMapper.readValue(json, Temp.class);
Map<?, ?> originalJsonMap = objectMapper.readValue(json, Map.class);
JsonNode generatedObjMap = objectMapper.valueToTree(generatedObj);
JsonNode originalObjMap = objectMapper.valueToTree(originalJsonMap);
Assert.assertSame(originalObjMap, generatedObjMap);
}
}
上述测试用例失败,断言错误为java.lang.AssertionError: JSON documents are different: Different keys found in node "". Expected [dblValue], got []. Missing: "dblValue"
但是当我将String json = "{\"dblValue\":0.0}";
更改为String json = "{\"dblValue\":1.0}";
时,测试就会通过。
我认为Double与Jackson一起使用默认值行为时,我无法解决并解决上述问题。杰克逊v2.8.10。
答案 0 :(得分:2)
问题出在这里:
objectMapper.setSerializationInclusion(Include.NON_DEFAULT);
双精度值0.0被视为默认值,而Jackson忽略了它。删除此行后,一切都应正常工作。如果您不希望包含布尔有效=假,请为有效字段添加 @JsonInclude 注释,如下所示:
@JsonInclude(Include.NON_DEFAULT)
boolean valid = false;