
spring boot中的@requestbody如何接受非json格式字符串参数?
问题:
如何使用@requestbody注解接收非json格式的字符串参数?例如,请求参数为"90c8c36f23a94c1487851129aa47d690/90c8c36f23a94c1487851129aa47d690"。
解答:
spring boot使用@requestbody注解将请求主体解析为json对象。如果请求体不是json格式,则会导致无法解析的错误。要接受非json格式的字符串,可以采取以下方法:
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
可以通过在spring boot应用程序中将spring.jackson.parser.disable-unwrapped-values属性设置为true来取消json解析。这将允许@requestbody解析纯字符串值,但会禁用所有其他未包装值(例如,int、boolean)。
spring:
jackson:
parser:
disable-unwrapped-values: true另一种方法是修改请求的content-type标头。将content-type设置为text/plain或application/octet-stream等非json值将指示spring boot不要将请求主体解析为json。
@postmapping(value = "/sendnews", consumes = "text/plain")
public string sendcontent(string lstmsgid) {
// ...
}也可以创建自定义http消息转换器来处理非json格式的字符串。这需要实现httpmessageconverter<t>接口并注册转换器到spring mvc。
// 自定义非JSON字符串转换器
public class PlainStringHttpMessageConverter implements HttpMessageConverter<String> {
@Override
public boolean canRead(Class<?> clazz, MediaType mediaType) {
return String.class.equals(clazz) && !mediaType.includes(MediaType.APPLICATION_JSON);
}
@Override
public boolean canWrite(Class<?> clazz, MediaType mediaType) {
return false;
}
@Override
public List<MediaType> getSupportedMediaTypes() {
return Collections.singletonList(MediaType.TEXT_PLAIN);
}
@Override
public String read(String cls, HttpInputMessage inputMessage) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputMessage.getBody()));
return reader.readLine();
}
@Override
public void write(String t, MediaType contentType, HttpOutputMessage outputMessage) {
throw new UnsupportedOperationException();
}
}
// 注册转换器
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new PlainStringHttpMessageConverter());
}
}通过这些方法,spring boot应用程序可以接受和处理非json格式的字符串作为@requestbody参数。
以上就是Spring Boot @RequestBody如何接收非JSON格式字符串参数?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号