4 回答

TA貢獻(xiàn)1812條經(jīng)驗(yàn) 獲得超5個贊
這可能對你有幫助。我有類似的情況,我使用這種方法將數(shù)據(jù)轉(zhuǎn)換為特定的需求。
public class MyCriteria {
public MyCriteria(LocalDate from, LocalDate till, Long communityNumber, String communityName){
// assignement of variables
}
private LocalDate from;
private LocalDate till;
private Long communityNumber;
private String communityName;
}
因此,每當(dāng)您從 JSON 創(chuàng)建對象時,它都會根據(jù)要求創(chuàng)建它。
當(dāng)我實(shí)現(xiàn)這個時,我使用“Jackson”的 ObjectMapper 類來完成此操作。希望你也能使用同樣的方法。

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個贊
在 pojo 類中使用 java.sql.Date 。就像 private Date from 一樣。我希望它能用于 JSON 轉(zhuǎn)換。當(dāng)您從 UI 接收日期 JSON 字段時,請始終使用 Java.sql.Date 進(jìn)行 Jackson 日期轉(zhuǎn)換。

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超8個贊
問題的答案是使用 init binder 來注冊指定條件內(nèi)的類型映射。需要PropertyEditorSupport針對特定目的進(jìn)行實(shí)施。
短代碼示例是:
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(LocalDate.parse(text, DateTimeFormatter.ISO_LOCAL_DATE));
}
});
}
完整的代碼示例可以從github獲?。?/p>
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.vl.example.rest.dtofromoaramsandpath.web.dto.MyCriteriaLd;
import java.beans.PropertyEditorSupport;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
@RestController
@RequestMapping("verify/criteria/mapping")
@Slf4j
public class MyControllerLd {
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(LocalDate.parse(text, DateTimeFormatter.ISO_LOCAL_DATE));
}
});
}
@GetMapping("community/{communityNumber}/dtold")
public MyCriteriaLd loadDataByDto(MyCriteriaLd criteria) {
log.info("received criteria: {}", criteria);
return criteria;
}
}
因此,這種情況的模型可以是下一個:
import lombok.Data;
import java.time.LocalDate;
@Data
public class MyCriteriaLd {
private LocalDate from;
private LocalDate till;
private Long communityNumber;
private String communityName;
}

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超6個贊
為此,您需要添加jsr310依賴項(xiàng)。
compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.8.10")
我希望這對你有用。
添加回答
舉報(bào)