spring接收json格式的多個物件引數(變通法)
阿新 • • 發佈:2019-01-26
兩種方法
方法1
如果使用spring mvc同客戶端通訊,完全使用json資料格式,需要如下定義一個RequestMapping
@Controller public class TestController{ @RequestMapping("\test") @ResponseBody public RetureResult test(@RequestBody User user){ return new ReturnResult(); } }
這樣,可以將json格式的資料轉換為指定的物件user,比如{name:"test"},name為User類的屬性值,也可以返回json格式的資料。
但是有時接收json格式資料時,我們可能需要將其轉換為多個物件,以上方式是不支援在方法變數中直接定義多個傳參的,以下方式是錯誤的。原因是request的body是以流的形式進行讀取的,讀取完一次後,便無法再次讀取了。
@Controller
public class TestController{
@RequestMapping("\test")
@ResponseBody
public RetureResult test(@RequestBody User user,@RequestBody Address address){
return new ReturnResult();
}
}
此時可使用一種變通的方法達到此目的。
在TestController.java檔案中增加一個包裝類
@Controller public class TestController{ @RequestMapping("\test") @ResponseBody public RetureResult test(@RequestBody Param param){ return new ReturnResult(); } } class Param{ public User user; public Address address; }
注意:類中屬性必須為public;Param類中的屬性只能比json中的屬性多,不能少
此時傳輸的json資料格式變為{user:{name:"test"},address:{location:"新華路"}}。
由於只是在TestController中增加一個包裝類,不會影響其他的類以及已經定義好的model類,因此可以非常方便的達到接收多個物件引數的目的。
方法2
將接收引數定義為Map<String, Object>,然後使用json轉object工具,轉換成需要的物件。
此時,即使自定義的Param類中的屬性只能比json資料中的屬性少了,也沒關係。
其中JSONUtils為自定義的工具類,可使用常見的fastjson等工具包包裝實現。
@Controller public class TestController{ @RequestMapping("\test") @ResponseBody public Object test(@RequestBody Map<String, Object> models){ User user=JsonXMLUtils.map2object((Map<String, Object>)models.get("user"),User.class);
Address address=JsonXMLUtils.map2object((Map<String, Object>)models.get("address"),Address.class);
return models;
}
}
import com.alibaba.fastjson.JSON;
public class JsonXMLUtils { public static String obj2json(Object obj) throws Exception { return JSON.toJSONString(obj); } public static <T> T json2obj(String jsonStr, Class<T> clazz) throws Exception { return JSON.parseObject(jsonStr, clazz); } public static <T> Map<String, Object> json2map(String jsonStr) throws Exception { return JSON.parseObject(jsonStr, Map.class); } public static <T> T map2obj(Map<?, ?> map, Class<T> clazz) throws Exception { return JSON.parseObject(JSON.toJSONString(map), clazz); } }