据我所知,spring boot有两种在请求参数中传递数组的方法:
逗号分隔值,例如: numbers=1,2,3,4,5
重复的参数名称,例如: numbers=1&numbers=2&numbers=3&numbers=4&numbers=5
在下面的示例中,它首先尝试使用方法1转换数组。然后在异常之后,它使用方法2成功地将其转换。
我的问题是:
有没有办法告诉SpringBoot只使用方法2。?
或者,是否有任何方法可以转义作为请求参数传递的json字符串中的逗号 x-www-form-urlencoded
内容类型?
demoobject.class:类:
public class DemoObject {
private String name;
private String description;
private Integer count;
//Constructor, Getters and Setters
}
democontroller.class:
@RestController
public class DemoController {
@PostMapping("test")
String test(@RequestParam List<DemoObject> objects, @RequestParam Integer number) throws JsonProcessingException {
return "["+number +"] " +om.writerWithDefaultPrettyPrinter().writeValueAsString(objects);
}
}
democonverter.class类:
@Component
public class DemoConverter implements GenericConverter {
private final ObjectMapper om = new ObjectMapper();
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
Set<ConvertiblePair> convertibles = new HashSet<>();
convertibles.add(new ConvertiblePair(String.class, DemoObject.class));
return convertibles;
}
@Override
public Object convert(Object o, TypeDescriptor sourceType, TypeDescriptor targetType) {
try {
return om.readValue((String) o, targetType.getType());
} catch (JsonProcessingException ex) {
Logger.getLogger(DemoConverter.class.getName()).log(Level.SEVERE, null, ex);
throw new RuntimeException("Conversion failed");
}
}
}
样品请求1:
POST http://localhost:8080/test
Body x-www-form-urlencoded
objects:{"name":"test","description":"AAA"}
number:123
spring boot引发异常:
com.fasterxml.jackson.core.io.JsonEOFException:
Unexpected end-of-input: expected close marker for Object
(start marker at [Source: (String)"{"name":"test""; line: 1, column: 1])
但结果是正确的,状态代码是200。
样品请求2:
POST http://localhost:8080/test
Body x-www-form-urlencoded
objects:{"name":"test","description":"AAA"}
objects:{"name":"test2","description":"BBB"}
number:123
无异常,状态200,结果正确。
谢谢你的帮助。
暂无答案!
目前还没有任何答案,快来回答吧!