Spring Boot @RequestBody如何接收非JSON格式字符串参数?(字符串.接收.参数.格式.Boot...)

wufei123 发布于 2025-01-09 阅读(22)

spring boot @requestbody如何接收非json格式字符串参数?

spring boot中的@requestbody如何接受非json格式字符串参数?

问题:

如何使用@requestbody注解接收非json格式的字符串参数?例如,请求参数为"90c8c36f23a94c1487851129aa47d690/90c8c36f23a94c1487851129aa47d690"。

解答:

spring boot使用@requestbody注解将请求主体解析为json对象。如果请求体不是json格式,则会导致无法解析的错误。要接受非json格式的字符串,可以采取以下方法:

  1. 取消json解析:

可以通过在spring boot应用程序中将spring.jackson.parser.disable-unwrapped-values属性设置为true来取消json解析。这将允许@requestbody解析纯字符串值,但会禁用所有其他未包装值(例如,int、boolean)。

spring:
  jackson:
    parser:
      disable-unwrapped-values: true
  1. 修改请求content-type:

另一种方法是修改请求的content-type标头。将content-type设置为text/plain或application/octet-stream等非json值将指示spring boot不要将请求主体解析为json。

@postmapping(value = "/sendnews", consumes = "text/plain")
public string sendcontent(string lstmsgid) {
    // ...
}
  1. 使用自定义http消息转换器:

也可以创建自定义http消息转换器来处理非json格式的字符串。这需要实现httpmessageconverter接口并注册转换器到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格式字符串参数?的详细内容,更多请关注知识资源分享宝库其它相关文章!

标签:  字符串 接收 参数 

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。