Ramu
Ramu

Reputation: 121

jackson serialization is excluding double value 0.0

When trying to map/set double value as 0.0, ObjectMapper is treating it as equivalent to null and thereby excluding when comparing for equality.

I have below test case:

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);
  }
}

The above test case is failing with assertion error as java.lang.AssertionError: JSON documents are different: Different keys found in node "". Expected [dblValue], got []. Missing: "dblValue"

But when I change the String json = "{\"dblValue\":0.0}"; as String json = "{\"dblValue\":1.0}";, test goes through.

I think there is something going on with default value behavior of Double in conjunction with Jackson, which I am unable to figure it out and solve my above issue. Jackson v2.8.10.

Upvotes: 6

Views: 2828

Answers (1)

bhusak
bhusak

Reputation: 1390

Problem here is with:

objectMapper.setSerializationInclusion(Include.NON_DEFAULT);

Double value 0.0 is considered as a default one and Jackson ignores it. After removing this line everything should work. If you don't want boolean valid = false to be included add @JsonInclude annotation for valid field like this:

@JsonInclude(Include.NON_DEFAULT)
boolean valid = false;

Upvotes: 5

Related Questions