Search code examples
javaspring-bootjacksonjackson-databind

Jackson ObjectMapper converts Integer value to null when mapped to Double type field in POJO


Please bear with me. I have gone through a lot of links but I am not able to find the solution for my case. I need help.

Note: I can not change the JSON request (represented in Test as map)

Here is my POJO:

public class TestModelWithDoubleField {
    private Double frequency;

    public Double getFrequency(){
        return frequency;
    }

    /**
     * @param frequency the frequency to set
     */
    public void setFrequency(Double frequency) {
        this.frequency = frequency;
    }

    /**
     * @param frequency the frequency to set
     */
    @JsonIgnore
    public void setFrequency(Integer frequency) {
        if(frequency != null) {
            setFrequency(new Double(frequency));
        }
    }
}

Here is the test which is failing:

@Test
public void testWithIntegerValueConvertToDoubleFieldInPOJO() throws IOException {
    final Map<String, Integer> map = new HashMap<>();
    map.put("frequency", 900);
    TestModelWithDoubleField pojo = objectMapper.convertValue(map, TestModelWithDoubleField.class);
    Assert.assertNotNull(pojo);
    Assert.assertNotNull(pojo.getFrequency());   //-> This is giving output as null. Hence fails.
}

In the line Assert.assertNotNull(pojo.getFrequency()); frequency is null. Hence the test fails.

I want that it is automatically converted to its Double type. Putting @JsonIgnore on the other setter also didn't work.

Any approach to get a valid object out of this map is fine.


Solution

  • Just add @JsonProperty("frequency") on the desired setter. You don't even need @JsonIgnore on the other one.

    public static class TestModelWithDoubleField
    {
      private Double frequency;
    
      public Double getFrequency()
      {
          return frequency;
      }
    
      /**
       * @param frequency the frequency to set
       */
      @JsonProperty("frequency")
      public void setFrequency(Double frequency)
      {
          this.frequency = frequency;
      }
    
      /**
       * @param frequency the frequency to set
       */
      public void setFrequency(Integer frequency)
      {
          if(frequency != null)
          {
              setFrequency(new Double(frequency));
          }
      }
    }