服务端接收到json数据转多种对象的两种处理

代码

![@RequestMapping(value="/handle_user.do", method=RequestMethod.POST)
	@ResponseBody
	public ResponseResult handleUser(@RequestBody Map param){
		MultiParams params = new MultiParams();
		params.setUser(JSONObject.parseObject(JSONObject.toJSONString(param.get("user")), User.class));
		params.setCar(JSONObject.parseObject(JSONObject.toJSONString(param.get("car")), UserCar.class));
		params.setWork(JSONObject.parseObject(JSONObject.toJSONString(param.get("work")), UserWork.class));
		params.setRelationship(JSONObject.parseObject(JSONObject.toJSONString(param.get("relationship")), UserRelationship.class));
		params.setColleague(JSONObject.parseObject(JSONObject.toJSONString(param.get("colleague")), UserColleague.class));
		params.setFood(JSONObject.parseObject(JSONObject.toJSONString(param.get("food")), UserFood.class));
		params.setHobby(JSONObject.parseObject(JSONObject.toJSONString(param.get("hobby")), UserHobby.class));
		User user = (User) getEntity("user", User.class);
		UserCar car = (UserCar) getEntity("car", UserCar.class);
		UserColleague colleague = (UserColleague) getEntity("colleague", UserColleague.class);
		UserFood food = (UserFood) getEntity("food", UserFood.class);
		UserHobby hobby = (UserHobby) getEntity("hobby", UserHobby.class);
		UserRelationship relationship = (UserRelationship) getEntity("relationship", UserRelationship.class);
		UserWork work = (UserWork) getEntity("work", UserWork.class);
		userService.insertUser(params);
		return new ResponseResult();
	}
	
	private Object getEntity(String name, Class clazz){
		return JSONObject.parseObject(JSONObject.toJSONString(name), clazz);
	}](https://img-blog.csdnimg.cn/20190701150757328.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0FkZWVwdHJhcA==,size_16,color_FFFFFF,t_70)

@RequestBody 后的参数可以是一个Map也可以是一个实体类,若为实体类,则需要在该类中声明多个对象和get,set方法,若为Map则不需要中间对象也能将数据实例化到各个对象中。

你可能感兴趣的:(后端)