将JSON数据转换成对象

controller类:

@RequestMapping(value = "/sgsHelpSend/createOmsOrder", method = RequestMethod.POST)
	@ResponseBody
	public Object createOmsOrder(@RequestParam("memNo") final String memNo,
			final HttpServletRequest request ) {
		log.info("createOmsOrder paramters is memNo="+memNo);
		
		if (StringUtils.isEmpty(memNo)) {
			return new ResultDto().setStatus(FAILURE).setMessage(
					i18Util.getMassage("user.memNo.null"));
		}
		UcmpHelpSendOrderDto order = null;
		try {
			
			order = jsonUtil.resolveJson(request, REQUEST_KEY, UcmpHelpSendOrderDto.class);
			
		} catch (Exception e) {
			log.error("从request获取需要解析的JSON数据,转成相应对象error:"+e.getMessage());
			return jsonResultUtil.resultError(i18Util.getMassage("order.error.params"));
		}
		try {
			//调用帮我送同城配下单业务逻辑处理
			return helpSendOrderService.createHelpSendOrder(order, request);
			
		} catch (Exception e) {
			log.error("调用UCMP帮我送同城配新建订单error:");
			return jsonResultUtil.resultError();
		}
	}
工具类:

/**
	 * 从request获取需要解析的JSON数据,转成相应对象
	 *
	 * @param request
	 * @param requestParamsKey
	 * @param objClass
	 * @return
	 * @throws Exception
	 */
	public  T resolveJson(HttpServletRequest request, String requestParamsKey, Class objClass) throws Exception {
			String jsonStr = request.getParameter(requestParamsKey);
			return resolveJson(jsonStr, objClass);
	}

/**
	 * 将JSON数据转换成对象
	 *
	 * @param jsonStr
	 * @param objClass
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public  T resolveJson(String jsonStr, Class objClass) throws Exception {
		try {
			if (StringUtils.isEmpty(MyStringUtil.nullToStr(jsonStr))) {
				return null;
			}
			JSONObject json = JSONObject.fromObject(jsonStr);
			return (T)JSONObject.toBean(json, objClass);
		} catch (Exception e) {
			log.error(e.getMessage());
			throw new Exception(e);
		}
	}


你可能感兴趣的:(Java)