Double Type formatter in Spring REST

Viewed 127

I have Model Class of Type Mileage That is declared as the following

public class Mileage extends Entity {
    @JsonProperty("mileageValue")
    private double mileageValue;

    @JsonProperty("mileageTime")
    private long mileageTime;
}

and the Code of the REST Controller method is as the following

  public ResponseEntity<Mileage> getMileage(@RequestBody GetRequest req) throws Exception {
        Mileage m1 = new Mileage();
        m1.setMileageTime(10);
        m1.setMileageValue(11111.11111);
        return new ResponseEntity<>(m1, HttpStatus.OK);
    }

As you see the mileageValue property is set to Double, when i use this line

m1.setMileageTime(10.0);

The repsonse in swagger will be like that

 {
  "mileageValue": 11111.11111,
  "mileageTime": 10
}

As you Can see the Deicmal Point with zero on its left has been trimmed and became like 10 instead of 10.0, is there a way to make it appears like 10.0 without formatting it as a String?

1 Answers

The current code which you have mentioned won't compile it expects long and you are passing it as double.

Please find my solution below:

@GetMapping("/test")
    public Mileage test() {
        Mileage m1 = new Mileage();
        m1.setMileageTime(10.0);
        m1.setMileageValue(11111.11111);
        return m1;
    }

    static class Mileage  {

        @Getter
        @Setter
        @JsonProperty("mileageValue")
        private double mileageValue;

        @Getter
        @Setter
        @JsonProperty("mileageTime")
        @JsonSerialize(using = DecimalJsonSerializer.class)
        private double mileageTime;
    }

    static class DecimalJsonSerializer extends JsonSerializer<Double> {
        @Override
        public void serialize(Double value, JsonGenerator jgen, SerializerProvider provider)
                throws IOException, JsonProcessingException {
            jgen.writeString( String.format("%.2f", value));
        }
    }

Response:

{
    "mileageValue": 11111.11111,
    "mileageTime": "10.00"
}

Linked Issue:

Why is Double with zero decimal value is omitted during jackson serialization?

Related