spring mvc前台传json值 后台接受处理成object

var jsonData = jsonToStr($('#addForm').serializeArray());//json数据
		$.ajax({
			type:"POST",
			url:"service/basic/department/add.json",
			dataType:"json",
			data:"_data_=" + jsonData,
			success: function(data) {
				if (!data.result) {
          			alert(data.remark);
          		} else {
          			alert("添加部门成功...");
          			window.returnValue = "success";
          			window.close();
           		}
			},
			error:function(error) {
				alert("操作失败:error message:" + error.statusText);
			}
		});




因为后台定义的接受格式是_data_;所以data:"_data_"+ json;
@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String create(HttpServletRequest request, Model model) {
		ResponseVO<Department> response = new ResponseVO<Department>();
		try {
			Department department = DataMapping.mapping(request, Department.class);
			// 前台设置仓库改为后台设置仓库。。
			Warehouse warehouse = new Warehouse();
			warehouse.setId(DataMapping.getWareHourse(request).getId());
			department.setWarehouse(warehouse);
			department = departmentService.create(department);
			response.setResult(true);
			Department data = new Department();
			data.setId(department.getId());
			response.setData(data);
		} catch (Exception ex) {
			log.error("Exception", ex);
			AppException exception = ExceptionHandleUtil.handle(ex);
			response.setResult(false);
			response.setCode(exception.getCode());
			response.setRemark(exception.getMessage());
			ex.printStackTrace();
		}
		model.addAttribute(response);
		return "success";
	}

public static <T> T mapping(HttpServletRequest request, Class<T> clazz) throws Exception {
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
		String data = request.getParameter("_data_");
		return objectMapper.readValue(data, clazz);
	}

json中的key对应实体类中的属性必须保持一致


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值