Search code examples
javajsonspring-bootdoubleresponse

How to convert Double to string in json output


I have an object which is given below:

public class Statics {
private Double sum;
private Double avg;
private Double max ;
private Double min ;
private Long count = Long.valueOf(0);//getter and setters and constructrures}

and I have a controller which return this object:

  @GetMapping("/statistics")
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<?> getStatics(){

    return ResponseEntity.status(HttpStatus.OK).body(staticService.getStatics());
}

and the service implementation is :

        private Statics statistics;
        
                public Statics getStatics() {
                if (statistics == null) {
                    Dou
    
    ble Zero =BigDecimal.valueOf(0.00).setScale(2, RoundingMode.HALF_UP).doubleValue();
                statistics = new Statics(Zero, Zero, Zero, Zero, Long.valueOf(0));
            }
            return statistics;
        }
 @Async
    public void statisticAnalysis() {

        DoubleSummaryStatistics stat = TRANSACTION_LIST.stream().mapToDouble(Transaction::getAmount)
                .summaryStatistics();
        statistics = new Statics(BigDecimal.valueOf(stat.getSum()).setScale(2, RoundingMode.HALF_UP).doubleValue(), BigDecimal.valueOf(stat.getAverage()).setScale(2, RoundingMode.HALF_UP).doubleValue(), BigDecimal.valueOf(stat.getMax()).setScale(2, RoundingMode.HALF_UP).doubleValue(), BigDecimal.valueOf(stat.getMin()).setScale(2, RoundingMode.HALF_UP).doubleValue(), stat.getCount());

    }

I want my output to be like the expected one in the mage that I will attach below,[ "sum": "100" in double quotation] but it always returns the number without quotations, what should I do? enter image description here


Solution

  •     public class Statics {
        @JsonFormat(shape = JsonFormat.Shape.STRING)
        private Double sum;
        @JsonFormat(shape = JsonFormat.Shape.STRING)
        private Double avg;
        @JsonFormat(shape = JsonFormat.Shape.STRING)
        private Double max ;
        @JsonFormat(shape = JsonFormat.Shape.STRING)
        private Double min ;
        private Long count = Long.valueOf(0);
    }
    

    Using this annotation: @JsonFormat(shape = JsonFormat.Shape.STRING) Solved my problem!