Spring Boot 2处理表单数据,其中json是键的值

时间:2019-01-16 16:11:34

标签: json spring-boot

我遇到一种情况,我必须实现post方法来处理表单数据,其中json是键的值。每个JSON内部表示一个对象。

我可以通过RequestParam将json作为字符串获取,然后使用Jackson转换为对象。

    @RequestMapping(value = "/rest/patient", consumes = {"multipart/form-data"},
                                                produces = "application/json", method= RequestMethod.POST)  
    public ResponseEntity<?> savePatient(@RequestParam("patient") String patient ) {
       // convert to Patient instance using Jackson

    }

Spring启动中是否有现成的映射?

1 个答案:

答案 0 :(得分:1)

我认为没有现成的映射。

您可以将GenericConvertor添加到WebDataBinder使用的WebConversionService中。您将需要列出所有对象类型。类似于以下内容:

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.GenericConverter;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

@Component
public class JsonFieldConverter implements GenericConverter {

    @Autowired
    private ObjectMapper objectMapper;

    // Add a new ConvertiblePair for each type you want to convert json 
    // in a field to using the objectMapper. This example has Patient and Doctor
    private static Set<ConvertiblePair> convertibleTypes = new HashSet<>();
    static {
        convertibleTypes.add(new ConvertiblePair(String.class, Patient.class));
        convertibleTypes.add(new ConvertiblePair(String.class, Doctor.class));
    }

    @Override
    public Set<ConvertiblePair> getConvertibleTypes() {
        return convertibleTypes;
    }

    @Override
    public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
        try {
            return objectMapper.readValue(source.toString(), targetType.getType());
        } catch (Exception e) {
            // TODO deal with the error.
            return source;
        }

    }
}

还有一个@ControllerAdvice,可将其插入数据绑定器:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.format.WebConversionService;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;

@ControllerAdvice
public class JsonFieldConfig {

    @Autowired
    private JsonFieldConverter jsonFieldConverter;

    @InitBinder
    private void bindMyCustomValidator(WebDataBinder binder) {
        ((WebConversionService)binder.getConversionService()).addConverter(jsonFieldConverter);
    }

}