Spring REST 中的双类型格式化程序
Double Type formatter in Spring REST
我有型号 Class 类型 里程 声明如下
public class Mileage extends Entity {
@JsonProperty("mileageValue")
private double mileageValue;
@JsonProperty("mileageTime")
private long mileageTime;
}
REST Controller方法的代码如下
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);
}
如您所见,里程值 属性 设置为双倍,当我使用这条线时
m1.setMileageTime(10.0);
招摇的反应会是这样
{
"mileageValue": 11111.11111,
"mileageTime": 10
}
如您所见,左侧为零的 Deicmal Point 已被修剪并变成 10 而不是 10.0,有没有办法让它看起来像 10.0 而无需将其格式化为字符串?
您提到的当前代码不会编译它需要很长时间并且您将其作为双精度传递。
请在下面找到我的解决方案:
@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));
}
}
回复:
{
"mileageValue": 11111.11111,
"mileageTime": "10.00"
}
相关问题:
我有型号 Class 类型 里程 声明如下
public class Mileage extends Entity {
@JsonProperty("mileageValue")
private double mileageValue;
@JsonProperty("mileageTime")
private long mileageTime;
}
REST Controller方法的代码如下
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);
}
如您所见,里程值 属性 设置为双倍,当我使用这条线时
m1.setMileageTime(10.0);
招摇的反应会是这样
{
"mileageValue": 11111.11111,
"mileageTime": 10
}
如您所见,左侧为零的 Deicmal Point 已被修剪并变成 10 而不是 10.0,有没有办法让它看起来像 10.0 而无需将其格式化为字符串?
您提到的当前代码不会编译它需要很长时间并且您将其作为双精度传递。
请在下面找到我的解决方案:
@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));
}
}
回复:
{
"mileageValue": 11111.11111,
"mileageTime": "10.00"
}
相关问题: