1.列如下方代码是接口 是一个post 方法, data 是客户端的的json 对象。怎么实现自动转换呢?
package com.slightech.marvin.api.visitor.app.controller;
import com.google.common.collect.Maps;
import com.slightech.marvin.api.doc.annotation.*;
import com.slightech.marvin.api.doc.model.SupportClientType;
import com.slightech.marvin.api.tools.api.constants.ApiConstant;
import com.slightech.marvin.api.visitor.app.dto.CapacityPackageDTO;
import com.slightech.marvin.api.visitor.app.dto.GetCapacityPackageListDTO;
import com.slightech.marvin.api.visitor.app.dto.GetCapacityPayListDTO;
import com.slightech.marvin.api.visitor.app.dto.InitBuildingCapacityPackageDTO;
import com.slightech.marvin.api.visitor.app.response.GetPageDataListResponse;
import com.slightech.marvin.api.visitor.app.response.GetPayListResponse;
import com.slightech.marvin.api.visitor.app.service.CapacityPackageService;
import com.slightech.marvin.api.visitor.app.utils.Constant;
import com.slightech.marvin.api.visitor.app.vo.BusinessCapacityPackageVO;
import com.slightech.marvin.api.visitor.app.vo.CapacityPackageVO;
import com.slightech.marvin.api.visitor.app.vo.MiniPackagePayRuleVO;
import lombok.val;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* 容量套餐
*
* @author willardwang
* @date 2019/01/28
*/
@RequestMapping(value = "package", produces = "application/json;charset=UTF-8")
@RestController
@MarvinApiDoc(value = "套餐", order = 996)
public class CapacityPackageController extends BaseController {
private static Logger logger = LoggerFactory.getLogger(Constant.CAPACITY_PACKAGE_LOGGER_NAME);
@Autowired
private CapacityPackageService capacityPackageService;
/**
* 初始化套餐
*/
@RequestMapping(value = "init", method = RequestMethod.POST)
public String initBuildingPackage(@RequestParam("data") InitBuildingCapacityPackageDTO initBuildingCapacityPackageDTO) throws IOException {
logParams(initBuildingCapacityPackageDTO);
if (initBuildingCapacityPackageDTO.getBuildingId() == null || initBuildingCapacityPackageDTO.getBuildingId() == 0) {
logger.warn("缺少参数building_id");
return buildResponseParamLack();
}
if (initBuildingCapacityPackageDTO.getPackageList() == null || initBuildingCapacityPackageDTO.getPackageList().isEmpty()) {
logger.warn("缺少参数套餐数据");
return buildResponseParamLack();
}
capacityPackageService.initBuildingCapacityPackage(initBuildingCapacityPackageDTO);
return buildResponseSuccess();
}
}
2.自定义转换的Scanner 在Spring 启动的时候扫描Controller的接口方法,发现是data 方法的,自定义的了类,把当前转换类类型转入Set 中
package com.slightech.marvin.api.tools.api.data;
import com.slightech.marvin.api.tools.api.constants.ApiConstant;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.RequestParam;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.HashSet;
import java.util.Set;
/**
* @author willardwang
* @description data 自动转换
* @date 2019/05/24
*/
@Component
public class RequestJsonDataToBeanScanner implements BeanPostProcessor {
Set<Class> jsonToBeanClass = new HashSet<>();
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
Method[] methods = ReflectionUtils.getAllDeclaredMethods(bean.getClass());
if (methods != null) {
for (Method method : methods) {
Parameter[] pms = method.getParameters();
for (int i =0 ; i < pms.length; i++) {
Parameter parameter = pms[i];
RequestParam requestParam = parameter.getAnnotation(RequestParam.class);
if (requestParam != null && “data”.equals(requestParam.value())) {
String dataTypeName = parameter.getParameterizedType().getTypeName();
if (!dataTypeName.equals("java.lang.String")) {
jsonToBeanClass.add(method.getParameterTypes()[i]);
}
}
}
}
}
return bean;
}
public Set<Class> getJsonToBeanClass() {
return jsonToBeanClass;
}
}
3. BaseController 中加入我自定义转换器
package com.slightech.marvin.api.tools.api;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.slightech.marvin.api.tools.api.data.RequestJsonDataEditor;
import com.slightech.marvin.api.tools.api.data.RequestJsonDataToBeanScanner;
import com.slightech.marvin.api.tools.common.JsonUtil;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import java.io.IOException;
import java.util.Set;
/**
* @author liuyang
*/
public abstract class BaseController {
@Autowired
RequestJsonDataToBeanScanner requestJsonDataToBeanScanner;
@InitBinder
public void InitBinder(WebDataBinder binder) {
Set<Class> classSet = requestJsonDataToBeanScanner.getJsonToBeanClass();
for (Class clazz : classSet) {
RequestJsonDataEditor requestJsonDataEditor = new RequestJsonDataEditor(clazz);
binder.registerCustomEditor(clazz, requestJsonDataEditor);
}
}
}
4. 转换代码
package com.slightech.marvin.api.tools.api.data;
import com.slightech.marvin.api.tools.common.JsonUtil;
import java.beans.PropertyEditorSupport;
import java.io.IOException;
/**
* @author willardwang
* @description
* @date 2019/05/16
*/
public class RequestJsonDataEditor extends PropertyEditorSupport {
private Class clazz;
public RequestJsonDataEditor(Class clazz) {
this.clazz = clazz;
}
@Override
public String getAsText() {
return getValue().toString();
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
try {
setValue(JsonUtil.jsonStr2Bean(text, this.clazz));
} catch (IOException e) {
throw new RuntimeException(text + "data 转 bean 异常");
}
}
}