4 回答

TA貢獻1812條經驗 獲得超5個贊
這可能對你有幫助。我有類似的情況,我使用這種方法將數據轉換為特定的需求。
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;
}
因此,每當您從 JSON 創建對象時,它都會根據要求創建它。
當我實現這個時,我使用“Jackson”的 ObjectMapper 類來完成此操作。希望你也能使用同樣的方法。

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

TA貢獻1818條經驗 獲得超8個贊
問題的答案是使用 init binder 來注冊指定條件內的類型映射。需要PropertyEditorSupport針對特定目的進行實施。
短代碼示例是:
@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貢獻1828條經驗 獲得超6個贊
為此,您需要添加jsr310依賴項。
compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.8.10")
我希望這對你有用。
添加回答
舉報