前端传输多个不同对象至后端
方式一、 使用form-urlencoded格式:
需要将对象转换为urlencoded格式,例如使用qs库或其他方式:
前端代码如下:Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
let data = qs. stringify ( {
newBaseMap: JSON . stringify ( this . form) ,
oldBaseMap: JSON . stringify ( this . oldForm)
} )
request ( {
url: '/test/modelEdit' ,
method: 'post' ,
headers: {
'Content-Type' : 'application/x-www-form-urlencoded;charset=utf-8'
} ,
data: data
} ) . then ( ( response ) => {
console. log ( "response" , response)
} )
在后端,首先将接收到的字符串参数反序列化为JSON对象,然后转化为BaseMap对象
@PostMapping ( "/test/modelEdit" )
public AjaxResult modelEdit (
@RequestParam ( "newBaseMap" ) String newBaseMapJson,
@RequestParam ( "oldBaseMap" ) String oldBaseMapJson
) {
ObjectMapper mapper = new ObjectMapper ( ) ;
BaseMap newBasMap = mapper. readValue ( newBaseMapJson, BaseMap . class ) ;
BaseMap oldBasMap = mapper. readValue ( oldBaseMapJson, BaseMap . class ) ;
}
方式二、 切换为JSON格式
前端代码如下: 'Content-Type': 'application/json;charset=utf-8'
let data = {
newBasMap: JSON . stringify ( this . form) ,
oldBasMap: JSON . stringify ( this . oldForm)
} ;
request ( {
url: '/test/modelEdit' ,
method: 'post' ,
headers: {
'Content-Type' : 'application/json;charset=utf-8'
} ,
data: data
} ) . then ( ( response ) => {
console. log ( "response" , response) ;
} ) ;
后端使用Map接收后使用ObjectMapper解析JSON对象:
@PostMapping ( "/test/modelEdit" )
public AjaxResult modelEdit ( @RequestBody Map < String , String > jsonPayload) {
ObjectMapper objectMapper = new ObjectMapper ( ) ;
try {
String newBaseMapJson = jsonPayload. get ( "newBaseMap" ) ;
BasMap newBaseMap = objectMapper. readValue ( newBasMapeJson, BasMap . class ) ;
String oldBaseMapJson = jsonPayload. get ( "oldBaseMap" ) ;
BasMap oldBaseMap = objectMapper. readValue ( oldBaseMapJson, BasMap . class ) ;
} catch ( JsonProcessingException e) {
}
}
后端使用JSONObject接收并解析JSON对象,映射到自定义对象仍需要ObjectMapper:
@PostMapping ( "/test/modelEdit" )
public AjaxResult modelEdit ( @RequestBody JSONObject jsonObject) {
try {
String newBaseMapJson = jsonObject. getString ( "newBaseMap" ) ;
BasMap newBaseMap = new ObjectMapper ( ) . readValue ( newBaseMapJson, BasMap . class ) ;
String oldBaseMapJson = jsonObject. getString ( "oldBaseMap" ) ;
BasMap oldBaseMap = new ObjectMapper ( ) . readValue ( oldBaseMapJson, BasMap . class ) ;
Boolean bool = jsonObject. getBoolean ( "bool" ) ;
List < Integer > dataList = jsonObject. getList ( "dataList" , Integer . class ) ;
} catch ( Exception e) {
}
}