請求類中的json字符串字段如何自動轉(zhuǎn)換(@RequestBody、@ModelAttribute)

該文章為原創(chuàng)(轉(zhuǎn)載請注明出處):請求類中的json字符串字段如何自動轉(zhuǎn)換(@RequestBody、@ModelAttribute) - 簡書 (jianshu.com)

使用場景

前端傳值:

{
    "userJson": "{\"phone\":\"123\",\"name\":\"xxx\"}"
}

為了支持前端的數(shù)據(jù)結(jié)構(gòu),后端做了妥協(xié),沒法使用對自己更方便更合理的結(jié)構(gòu)?

后端@RequestBody注解的類中的字段為 userJson 傳輸,需要在controller層手動處理

@GetMapping("test.do")
public RestResponse<Void> test(@RequestBody TestBody body) {
    body.setUser(JSON.parseObject(body.getUserJson(), User.class));
    // service.handleUser(body);
}
@Data
static class TestBody {
    private String userJson;
    private User user;
}
static class User {
    private String phone;
    private String name;
}

如何把邏輯提取到框架或者工具層面,實(shí)現(xiàn)自動裝配,無感使用對象 ?

1. 擴(kuò)展Jackson的反序列化器,轉(zhuǎn)換String到字段類型的對象

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
 
import java.io.IOException;
 
/**
 * @author uhfun
 * @see JsonDeserialize#using()
 */
public class JacksonStringToJavaObjectDeserializer extends JsonDeserializer<Object> implements ContextualDeserializer {
    private JavaType javaType;
 
    @Override
    public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        ObjectMapper mapper = (ObjectMapper) p.getCodec();
        String value = p.getValueAsString();
        return value == null ? null : mapper.readValue(value, javaType.getRawClass());
    }
 
    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) {
        javaType = property.getType();
        return this;
    }
}

2. 擴(kuò)展FastJson的反序列化器,轉(zhuǎn)換String到字段類型的對象

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
 
import java.lang.reflect.Type;
 
import static com.alibaba.fastjson.parser.JSONToken.LITERAL_STRING;
 
/**
 * @author uhfun
 * @see JSONField#deserializeUsing()
 */
public class FastJsonStringToJavaObjectDeserializer implements ObjectDeserializer {
    @Override
    public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
        String s = parser.parseObject(String.class);
        return JSON.parseObject(s, type);
    }
 
    @Override
    public int getFastMatchToken() {
        return LITERAL_STRING;
    }
}

如何使用擴(kuò)展的反序列化器

1. Jackson

@Data
static class TestBody {
    @JsonDeserialize(using = JacksonStringToJavaObjectDeserializer.class)
    private User userJson;
}

2. FastJson

@Data
static class TestBody {
    @JSONField(deserializeUsing = FastJsonStringToJavaObjectDeserializer.class)
    private User userJson;
}

@ModelAttribute如何支持自動綁定json字符串的字段 為 對象 ?

@GetMapping("test.do")
public RestResponse<Void> test(@ModelAttribute TestBody body) {
    body.setUser(JSON.parseObject(body.getUserJson(), User.class));
    // service.handleUser(body);
}
@Data
static class TestBody {
    private String userJson;
    private User user;
}
static class User {
    private String phone;
    private String name;
}

實(shí)現(xiàn)下面的切面,自動注冊需要轉(zhuǎn)換的轉(zhuǎn)換器

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.google.common.collect.Sets;
import org.springframework.boot.autoconfigure.web.format.WebConversionService;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.GenericConverter;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
 
import java.lang.reflect.Field;
import java.util.Set;
 
import static java.util.Collections.singleton;
 
/**
 * 使@ModelAttribute支持綁定Json字符串為對象
 *
 * @author uhfun
 * @see RequestMappingHandlerAdapter#initControllerAdviceCache()
 * 尋找@ControllerAdvice切面下@InitBinder注解的方法
 * @see org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#INIT_BINDER_METHODS
 * @see org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#getDataBinderFactory(org.springframework.web.method.HandlerMethod)
 * 根據(jù)切面構(gòu)建InitBinderMethod方法
 * @see org.springframework.web.method.annotation.InitBinderDataBinderFactory#initBinder
 * 初始化binder時反射調(diào)用
 * @see ModelAttribute
 */
@ControllerAdvice
public class StringToJsonObjectSupport {
    private static final Set<Class<?>> CONVERTER_INITIALIZED = Sets.newConcurrentHashSet();
 
    @InitBinder
    public void initStringJsonObjectConverter(WebDataBinder dataBinder) {
        Object target = dataBinder.getTarget();
        WebConversionService conversionService;
        if (dataBinder.getConversionService() instanceof WebConversionService) {
            conversionService = (WebConversionService) dataBinder.getConversionService();
            if (target != null && !CONVERTER_INITIALIZED.contains(target.getClass())) {
                for (Field field : dataBinder.getTarget().getClass().getDeclaredFields()) {
                    JSONField jsonField = AnnotationUtils.findAnnotation(field, JSONField.class);
                    boolean jsonFieldAnnotated = jsonField != null && jsonField.deserialize(),
                            deserializeAnnotated = jsonFieldAnnotated || AnnotatedElementUtils.hasAnnotation(field, JsonDeserialize.class);
                    if (deserializeAnnotated) {
                        Class<?> type = field.getType();
                        conversionService.addConverter(new JsonStringToObjectConverter(type));
                    }
                }
                CONVERTER_INITIALIZED.add(target.getClass());
            }
        } else {
            throw new IllegalStateException("dataBinder的ConversionService不是WebConversionService類型實(shí)例");
        }
    }
 
    static class JsonStringToObjectConverter implements GenericConverter {
 
        private final Class<?> targetType;
 
        public JsonStringToObjectConverter(Class<?> targetType) {
            this.targetType = targetType;
        }
 
        @Override
        public Set<ConvertiblePair> getConvertibleTypes() {
            return singleton(new ConvertiblePair(String.class, targetType));
        }
 
        @Override
        public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
            return JSON.parseObject((String) source, targetType.getType());
        }
    }
}
@Data
static class TestBody {
    @JsonDeserialize
    private User userJson;
}

該文章為原創(chuàng)(轉(zhuǎn)載請注明出處):請求類中的json字符串字段如何自動轉(zhuǎn)換(@RequestBody、@ModelAttribute) - 簡書 (jianshu.com)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請通過簡信或評論聯(lián)系作者。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容