接口間數(shù)據(jù)傳輸
接口間數(shù)據(jù)傳輸問題
程序的接口之間進行信息通信的過程中,會遇到一些參數(shù)數(shù)據(jù)接收和轉(zhuǎn)換的問題。
例如:前端傳過來的一個實體數(shù)據(jù),其中包含另一個實體,且實體屬性中包含除string以外的其他類型(例如:date),這樣在接收的時候會出現(xiàn)各種異常情況。
java實體示例:
@Data public class Person { @FieldName("轉(zhuǎn)貨單據(jù)頭") private Integer fid; @FieldName("發(fā)貨公司系統(tǒng)更新時間") @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="GMT+8") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date sendUpdateSysDate; @FieldName("是否推送TMS收貨公司 0否1是2預(yù)上線") private Integer tmsReceiveSwitch; @FieldName("收貨公司系統(tǒng)更新時間") @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="GMT+8") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date ReceiveUpdateSysDate; @FieldName("轉(zhuǎn)貨單體") private List<Personentry> personEntryList; }
前端傳遞數(shù)據(jù):
1 { 2 "fid": 0, 3 "sendUpdateSysDate": "2020-10-11 16:15:15", 4 "tmsReceiveSwitch": 0, 5 "ReceiveUpdateSysDate": "2020-10-11 16:15:15", 6 "personEntryList": [{ 7 "fid": 0, 8 "fparentid": 0, 9 "fentryid": 0, 10 "fitemid": 0}, 11 { 12 "fid": 0, 13 "fparentid": 0, 14 "fentryid": 0, 15 "fitemid": 0}, 16 ] 17 }
如上面所示,前端傳遞的json數(shù)據(jù),雖然和java實體是屬性一一對應(yīng)但是在Controller中進行接收:
1 @RequestMapping(value = "/api",method = RequestMethod.POST) 2 @ResponseBody 3 public RemoteResult valideTransferTime(@RequestBody Person p){ 4 logger.info(String.format(">>>>>>>>>>>>>>>>>>>>>>>入?yún)ⅲ篭n[%s]",p.toString())); 5 return transferService.valideTransferTime(p); 6 }
報錯如下:

出現(xiàn)上面的問題是由于json中字段和實體字段不對應(yīng)(包括屬性個數(shù)和類型)導(dǎo)致的。雖然Json中的字段和實體中的是一一對應(yīng)的,但是在前端Json傳遞到后端后通過實體進行接收,實體中的Date類型,前端傳過來的是字符串,導(dǎo)致類型不一致,無法接收。如上面代碼中標紅的代碼。
解決方案:
方案一、通過配置解決(本人在使用方案一后仍然未解決問題):
在實體屬性上使用這個兩個注解中的一個,用java.util.Date;和java.sql.Date都行
@JsonFormat(pattern=“yyyy-MM-dd HH:mm:ss”, timezone=“GMT+8”)
@DateTimeFormat(pattern=“yyyy-MM-dd HH:mm:ss”)
在spring配置文件中配置
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
方案二、通過JSONObject接收,然后解析成實際使用的實體:
1 public RemoteResult valideTransferTime(@RequestBody JSONObject jsonObject){ 2 Person p=JSONObject.parseObject(jsonObject.toJSONString(),Person.class); 3 logger.info(String.format(">>>>>>>>>>>>>>>>>>>>>>>入?yún)ⅲ篭n[%s]",p.toString())); 4 return personService.valideTransferTime(p); 5 }
本人強烈推薦使用第二種方案,第二種方案可控度高并且問題排查比較容易,而且非常靈活。非常不推薦使用直接的實體作為DTO進行數(shù)據(jù)的傳輸和接收。
本文來自博客園,作者:藍迷夢,轉(zhuǎn)載請注明原文鏈接:http://www.rzrgm.cn/hewei-blogs/p/13838876.html

浙公網(wǎng)安備 33010602011771號