SpringBoot2处理表单数据,其中json是键的值
在这种情况下,我必须实现post方法来处理表单数据,其中json是键的值。每个JSON在内部表示一个对象 我可以通过RequestParam获取json作为字符串,然后使用Jackson转换为objectSpringBoot2处理表单数据,其中json是键的值,json,spring-boot,Json,Spring Boot,在这种情况下,我必须实现post方法来处理表单数据,其中json是键的值。每个JSON在内部表示一个对象 我可以通过RequestParam获取json作为字符串,然后使用Jackson转换为object @RequestMapping(value = "/rest/patient", consumes = {"multipart/form-data"}, produces = "applic
@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
}
@RequestMapping(value=“/rest/patient”,使用={“多部分/表单数据”},
products=“application/json”,method=RequestMethod.POST)
public ResponseEntity savePatient(@RequestParam(“patient”)字符串patient){
//使用Jackson转换为患者实例
}
Spring boot是否有现成的映射?我不相信有现成的映射 您可以向WebDataBinder使用的WebConversionService添加GenericConverter。您需要列出所有对象类型。如下所示:
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;
}
}
}
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);
}
}