从模型获取指定数据作为带注释的JSON响应

时间:2018-12-03 18:14:17

标签: java json spring spring-mvc spring-boot

我想获取带有一些批注的JSON响应。例如,现在我在json中的响应如下:

{
"id": 1,
"startDate": [
    1993,
    12,
    12
],
"endDate": [
    2018,
    11,
    22
],
"totalDistance": 255,
"totalPrice": 211
}

但是我想从模型中选择数据并为它们添加注释,例如单位或更改日期类型格式。这就是我希望得到的json响应:

{
"startDate": "December, 12th",
"totalDistance": "255 km",
"totalPrice": "211 Euros",
}

这是我的ApiController的一部分:

 @RequestMapping(path = "/api/reports/daily", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE, produces = "application/json")
public Reports getDailyReport1(@RequestParam("start_date") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate  , @RequestParam("end_date") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
    Reports reports = new Reports();
    reports.setStartDate(startDate);
    reports.setEndDate(endDate);
    reportsService.calculateTotalDistance(reports);
    reportsService.calculateTotalPrice(reports);
    return reports;
}

@GetMapping(value = "/api/reports/{id}", produces = "application/json")
public Optional<Reports> getReportsFromId(@PathVariable Long id){
    return reportsService.getReport(id);
}

@GetMapping("/api/reports")
public Collection<Reports> getAllReports(){
    return reportsService.findAllReports();
}

服务:

@Service
public class ReportsService {

@Autowired
TransitService transitService;

@Autowired
ReportsRepository reportsRepository;


public void addReports(Reports reports) {
    reportsRepository.save(reports);
}


public void calculateTotalDistance(Reports reports) {
    double totalDistance = 0.0;
    List<Transit> transits = transitService.getTransits(reports.getStartDate(), reports.getEndDate());
    for (Transit transit : transits) {
        if (transit.getDistance() != null) {
            totalDistance = totalDistance + transit.getDistance();
        }
    }
    reports.setTotalDistance((long) totalDistance);
}


public void calculateTotalPrice(Reports reports) {
    double totalPrice = 0.0;
    List<Transit> transits = transitService.getTransits(reports.getStartDate(), reports.getEndDate());
    for (Transit transit : transits) {
        if (transit.getPrice() != null) {
            totalPrice = totalPrice + transit.getPrice();
        }
    }
    reports.setTotalPrice((long) totalPrice);
}

public void addReports1(Reports reports) {
    reportsRepository.save(reports);
}



public List<Reports> findAllReports() {
    Iterable<Reports> all = reportsRepository.findAll();
    List<Reports> reports = convertReportsToList(all);
    return reports;
}

private List<Reports> convertReportsToList(Iterable<Reports> all) {
    List<Reports> reports = new ArrayList<>();
    for (Reports report : all) {
        reports.add(report);
    }
    return reports;
}

public Optional<Reports> getReport(Long id){
    return reportsRepository.findById(id);
}

}

当我将@RequestMapping(path =“ / api / reports / daily”)更改为:

@RequestMapping(path = "/api/reports/daily", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE, produces = "application/json")
public String getDailyReport1(@RequestParam("start_date") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate  , @RequestParam("end_date") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
    Reports reports = new Reports();
    reports.setStartDate(startDate);
    reports.setEndDate(endDate);
    reportsService.calculateTotalDistance(reports);
    reportsService.calculateTotalPrice(reports);
    return "Total price" + reports.getTotalPrice + "Euros" + "Total distance" + reports.getTotalDistance + "km";

我从JSON获得响应。 J是否应该创建json响应模板并将其返回此处以获取我想要的信息,并带有诸如单位等的批注?感谢您的时间。希望你了解我的想法。

1 个答案:

答案 0 :(得分:0)

假设您使用的是Jackson,则可以根据需要添加自定义序列化程序以进行格式化。

例如创建一个DistanceSerializer

public class DistanceSerializer<T> extends StdSerializer<T> {

    public DistanceSerializer() {
        this(null);
    }

    protected DistanceSerializer(Class<T> t) {
        super(t);
    }

    @Override
    public void serialize(T value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeString(value + " km");
    }

}

并使用DistanceSerializer注释totalDistance字段

    @JsonSerialize(using=DistanceSerializer.class)
    private long totalDistance;