requestBody注解转化json报错

2023-11-01

@RequestBody, @ResponseBody 注解详解(转)

解决方法:不要用modelMap,新建一个hashMap类即可

进来给app写接口比较多,遇到一个bug,requestBody会自动往modelMap里加解决办法,清空map或者自己新建一个map

通过打断点,查看进入控制器的方法中各个对象实例的状态,发现正常程序与异常程序之间的区别:

把自定义类换成Java自带的封装类都能够正确运行;
当程序正常运行时,map是空的(不是null)。而异常程序的map包含两个值,一个是GStation对象的值,一个是org.springframework.validation.BindingResult.GStation=org.springframework.validation.BeanPropertyBindingResult: 0 errors

  因此做出大胆假设,出错的原因是ajax传递多值至对象中时,Spring MVC会在map里面增加两个值(一个是传输的数据对象,一个是对于对象属性绑定的验证结果),而这两个值是Jackson将map处理成json格式时出错 。通过Spring文档中的内容也验证了这一说法,内容如下:

Command or form objects to bind request parameters to bean properties (via setters) or directly to fields, with customizable type conversion, depending on@InitBinder methods and/or the HandlerAdapter configuration. See thewebBindingInitializer property on RequestMappingHandlerAdapter. Such command objects along with their validation results will be exposed as model attributes by default, using the command class class name - e.g. model attribute "orderAddress" for a command object of type "some.package.OrderAddress". The ModelAttribute annotation can be used on a method argument to customize the model attribute name used.

所以,只要map是空的(非null)就行了。
 

引言:

http://www.byywee.com/page/M0/S702/702424.html()

 

简介:

@RequestBody

作用: 

      i) 该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上;

      ii) 再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上。

使用时机:

A) GET、POST方式提时, 根据request header Content-Type的值来判断:

  •     application/x-www-form-urlencoded, 可选(即非必须,因为这种情况的数据@RequestParam, @ModelAttribute也可以处理,当然@RequestBody也能处理);
  •     multipart/form-data, 不能处理(即使用@RequestBody不能处理这种格式的数据);
  •     其他格式, 必须(其他格式包括application/json, application/xml等。这些格式的数据,必须使用@RequestBody来处理);

 

B) PUT方式提交时, 根据request header Content-Type的值来判断:

 

  •     application/x-www-form-urlencoded, 必须;
  •     multipart/form-data, 不能处理;
  •     其他格式, 必须;

说明:request的body部分的数据编码格式由header部分的Content-Type指定;

 

 

@ResponseBody

 

作用: 

      该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。

使用时机:

      返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;

 

 

 

HttpMessageConverter

复制代码

<span style="font-family:Microsoft YaHei;">/**
 * Strategy interface that specifies a converter that can convert from and to HTTP requests and responses.
 *
 * @author Arjen Poutsma
 * @author Juergen Hoeller
 * @since 3.0
 */
public interface HttpMessageConverter<T> {

    /**
     * Indicates whether the given class can be read by this converter.
     * @param clazz the class to test for readability
     * @param mediaType the media type to read, can be {@code null} if not specified.
     * Typically the value of a {@code Content-Type} header.
     * @return {@code true} if readable; {@code false} otherwise
     */
    boolean canRead(Class<?> clazz, MediaType mediaType);

    /**
     * Indicates whether the given class can be written by this converter.
     * @param clazz the class to test for writability
     * @param mediaType the media type to write, can be {@code null} if not specified.
     * Typically the value of an {@code Accept} header.
     * @return {@code true} if writable; {@code false} otherwise
     */
    boolean canWrite(Class<?> clazz, MediaType mediaType);

    /**
     * Return the list of {@link MediaType} objects supported by this converter.
     * @return the list of supported media types
     */
    List<MediaType> getSupportedMediaTypes();

    /**
     * Read an object of the given type form the given input message, and returns it.
     * @param clazz the type of object to return. This type must have previously been passed to the
     * {@link #canRead canRead} method of this interface, which must have returned {@code true}.
     * @param inputMessage the HTTP input message to read from
     * @return the converted object
     * @throws IOException in case of I/O errors
     * @throws HttpMessageNotReadableException in case of conversion errors
     */
    T read(Class<? extends T> clazz, HttpInputMessage inputMessage)
            throws IOException, HttpMessageNotReadableException;

    /**
     * Write an given object to the given output message.
     * @param t the object to write to the output message. The type of this object must have previously been
     * passed to the {@link #canWrite canWrite} method of this interface, which must have returned {@code true}.
     * @param contentType the content type to use when writing. May be {@code null} to indicate that the
     * default content type of the converter must be used. If not {@code null}, this media type must have
     * previously been passed to the {@link #canWrite canWrite} method of this interface, which must have
     * returned {@code true}.
     * @param outputMessage the message to write to
     * @throws IOException in case of I/O errors
     * @throws HttpMessageNotWritableException in case of conversion errors
     */
    void write(T t, MediaType contentType, HttpOutputMessage outputMessage)
            throws IOException, HttpMessageNotWritableException;

}
</span>

复制代码

该接口定义了四个方法,分别是读取数据时的 canRead(), read() 和 写入数据时的canWrite(), write()方法。

 

在使用 <mvc:annotation-driven />标签配置时,默认配置了RequestMappingHandlerAdapter(注意是RequestMappingHandlerAdapter不是AnnotationMethodHandlerAdapter,详情查看Spring 3.1 document “16.14 Configuring Spring MVC”章节),并为他配置了一下默认的HttpMessageConverter:

复制代码

    ByteArrayHttpMessageConverter converts byte arrays.

    StringHttpMessageConverter converts strings.

    ResourceHttpMessageConverter converts to/from org.springframework.core.io.Resource for all media types.

    SourceHttpMessageConverter converts to/from a javax.xml.transform.Source.

    FormHttpMessageConverter converts form data to/from a MultiValueMap<String, String>.

    Jaxb2RootElementHttpMessageConverter converts Java objects to/from XML — added if JAXB2 is present on the classpath.

    MappingJacksonHttpMessageConverter converts to/from JSON — added if Jackson is present on the classpath.

    AtomFeedHttpMessageConverter converts Atom feeds — added if Rome is present on the classpath.

    RssChannelHttpMessageConverter converts RSS feeds — added if Rome is present on the classpath.

复制代码

ByteArrayHttpMessageConverter: 负责读取二进制格式的数据和写出二进制格式的数据;

StringHttpMessageConverter:   负责读取字符串格式的数据和写出二进制格式的数据;

 

ResourceHttpMessageConverter:负责读取资源文件和写出资源文件数据; 

FormHttpMessageConverter:       负责读取form提交的数据(能读取的数据格式为 application/x-www-form-urlencoded,不能读取multipart/form-data格式数据);负责写入application/x-www-from-urlencoded和multipart/form-data格式的数据;

 

MappingJacksonHttpMessageConverter:  负责读取和写入json格式的数据;

 

SouceHttpMessageConverter:                   负责读取和写入 xml 中javax.xml.transform.Source定义的数据;

Jaxb2RootElementHttpMessageConverter:  负责读取和写入xml 标签格式的数据;

 

AtomFeedHttpMessageConverter:              负责读取和写入Atom格式的数据;

RssChannelHttpMessageConverter:           负责读取和写入RSS格式的数据;

 

当使用@RequestBody和@ResponseBody注解时,RequestMappingHandlerAdapter就使用它们来进行读取或者写入相应格式的数据。

 

HttpMessageConverter匹配过程:

@RequestBody注解时: 根据Request对象header部分的Content-Type类型,逐一匹配合适的HttpMessageConverter来读取数据;

spring 3.1源代码如下:

复制代码

private Object readWithMessageConverters(MethodParameter methodParam, HttpInputMessage inputMessage, Class paramType)
            throws Exception {

        MediaType contentType = inputMessage.getHeaders().getContentType();
        if (contentType == null) {
            StringBuilder builder = new StringBuilder(ClassUtils.getShortName(methodParam.getParameterType()));
            String paramName = methodParam.getParameterName();
            if (paramName != null) {
                builder.append(' ');
                builder.append(paramName);
            }
            throw new HttpMediaTypeNotSupportedException(
                    "Cannot extract parameter (" + builder.toString() + "): no Content-Type found");
        }

        List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>();
        if (this.messageConverters != null) {
            for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
                allSupportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes());
                if (messageConverter.canRead(paramType, contentType)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Reading [" + paramType.getName() + "] as \"" + contentType
                                +"\" using [" + messageConverter + "]");
                    }
                    return messageConverter.read(paramType, inputMessage);
                }
            }
        }
        throw new HttpMediaTypeNotSupportedException(contentType, allSupportedMediaTypes);
    }

复制代码

@ResponseBody注解时: 根据Request对象header部分的Accept属性(逗号分隔),逐一按accept中的类型,去遍历找到能处理的HttpMessageConverter;

源代码如下:

复制代码

private void writeWithMessageConverters(Object returnValue,
                HttpInputMessage inputMessage, HttpOutputMessage outputMessage)
                throws IOException, HttpMediaTypeNotAcceptableException {
            List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
            if (acceptedMediaTypes.isEmpty()) {
                acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
            }
            MediaType.sortByQualityValue(acceptedMediaTypes);
            Class<?> returnValueType = returnValue.getClass();
            List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>();
            if (getMessageConverters() != null) {
                for (MediaType acceptedMediaType : acceptedMediaTypes) {
                    for (HttpMessageConverter messageConverter : getMessageConverters()) {
                        if (messageConverter.canWrite(returnValueType, acceptedMediaType)) {
                            messageConverter.write(returnValue, acceptedMediaType, outputMessage);
                            if (logger.isDebugEnabled()) {
                                MediaType contentType = outputMessage.getHeaders().getContentType();
                                if (contentType == null) {
                                    contentType = acceptedMediaType;
                                }
                                logger.debug("Written [" + returnValue + "] as \"" + contentType +
                                        "\" using [" + messageConverter + "]");
                            }
                            this.responseArgumentUsed = true;
                            return;
                        }
                    }
                }
                for (HttpMessageConverter messageConverter : messageConverters) {
                    allSupportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes());
                }
            }
            throw new HttpMediaTypeNotAcceptableException(allSupportedMediaTypes);
        }

复制代码

补充:

MappingJacksonHttpMessageConverter 调用了 objectMapper.writeValue(OutputStream stream, Object)方法,使用@ResponseBody注解返回的对象就传入Object参数内。若返回的对象为已经格式化好的json串时,不使用@RequestBody注解,而应该这样处理:
1、response.setContentType("application/json; charset=UTF-8");
2、response.getWriter().print(jsonStr);
直接输出到body区,然后的视图为void。

 

参考资料:

 

1、 Spring 3.1 Doc: 

spring-3.1.0/docs/spring-framework-reference/html/mvc.html

2、Spring 3.x MVC 入门4 -- @ResponseBody & @RequestBody

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

requestBody注解转化json报错 的相关文章

  • vue-cli 方式创建 uni-app 项目(支持快捷键)

    文章目录 1 前言 2 创建 uni app 3 删除多余依赖 4 支持快捷键 5 安装 uni ui 及 sass 6 配置 easycom 7 运行 1 前言 由于习惯了 VSCode 的使用 本着快速交付 不需要转换开发思维 不需要更
  • 跟ChatGPT同源插件,专为测试人的开放,快来看看吧

    3 月 23 日 OpenAI 又投出了一枚重磅炸弹 为 ChatGPT 推出插件系统 此举意味着 ChatGPT 将迎来 APP Store 时刻 也就是围绕它的能力 形成一个开发者生态 打造出基于 AI 的 操作系统 插件系统将为 Ch
  • [知识图谱实战篇] 八.HTML+D3绘制时间轴线及显示实体

    前面作者讲解了很多知识图谱原理知识 包括知识图谱相关技术 Neo4j绘制关系图谱等 但仍缺少一个系统全面的实例 为了加深自己对知识图谱构建的认识 为后续创建贵州旅游知识图谱打下基础 作者深入学习了张宏伦老师的网易云课程 星球系列电影 并结合
  • Linux系统版本信息查看

    一 查看Linux内核版本命令 方法1 cat proc version root localhost cat proc version Linux version 3 10 0 957 el7 x86 64 mockbuild kbuil
  • 型号不同的计算机内存条可以通用么,笔记本内存条和台式机通用吗

    电脑分为笔记本和台式机 这两者里面都有一个很重要的部件就是内存条 虽然作用都是相同的 但两者却是不一样的 那么笔记本内存条和台式机通用吗 答案是不可以 下面小编会给大家详细介绍不能通用的原因 以及笔记本内存条怎么装 看型号等等问题 笔记本内
  • 【Chisel入门——数据类型与操作符号】

    文章目录 前言 Chisel开发环境部署 安装步骤 环境测试 实验环境问题说明 数据类型 UInt SInt Bool Vec T Bundle 操作符 总结 前言 前面的部分简单介绍了Chisel 新型敏捷硬件开发语言 也简单说明了开发环
  • 黑马并发编程JUC(信号量、线程安全类)总结

    黑马并发编程JUC总结 9 JUC Semaphore 定义 原理 acquire release CountDownLatch 为什么需要用到CountDownLatch 定义 为什么加载的时候需要使用到countDownLock 商品问
  • EsayExcle的简单使用

  • Linux应用编程

    孤儿进程 在Linux Unix环境中 我们是通过fork函数来创建子进程的 创建完毕之后 父子进程独立运行 父进程无法预知子进程什么时候结束 通常情况下 子进程退出后 父进程会使用wait或waitpid函数进行回收子进程的资源 并获得子
  • nginx-1.13.x源码安装

    Nginx 安装配置 依赖库 zlib 下载 http download chinaunix net download php id 24013 ResourceID 12241 pcre apt get install libpcre d
  • 地理坐标xy表示什么_地理坐标怎么写 书写格式及方法

    地理坐标怎么写 书写格式及方法 地理坐标是用纬度 经度表示地面点位置的球面坐标 地理坐标系以地 轴为极轴 所有通过地球南北极的平面均称为子午面 地理坐标 就是用经 纬度表示地面点位的球面坐标 1 地理坐标的概念子午面与地球椭球面的交线 称为
  • 代码解析工具汇总

    代码解析工具 一 针对多种语言 ANTLR SonarQube tree sitter 二 针对C语言 pycparser Joern 三 针对Java Javalang JavaParser Eclipse AstParser 四 针对p
  • java:方法重载和方法重写的区别

    方法重载 代码示例 public void set System out println 好好学习 public void set String name System out println 好好学习 方法重写 在不同的类中 在有继承关系
  • 服务器部署JavaWeb的war包(完整版)

    本文章内容操作环境采用的技术是docker部署war 提前下载好Xshell7 终端 如果你买的服务器有终端窗口 那么用你的服务器终端窗口也行 和Xftp7 传输文件 并下载navicat15 版本过低会因为1045 连不上服务器 一 导出
  • 网络基础:协议层次

    目录 一 理论 1 OSI参考模型 2 TCP IP模型 3 OSI模型对应协议 4 TCP IP模型对应协议 5 OSI模型传输数据过程 二 实验 1 TCP IP模型封装 一 理论 一个协议层能够用软件 硬件或者两者的结合来实现 各个层
  • 谷歌浏览器插件Automa_2.点击和输入文字

    操作 普通玩家对于组件的操作无非就输入文字 点击控件跳转页面 但高端玩家会为这些操作加上各种限制条件以让其适应各种网页 而这些内容将在进阶篇介绍 点击 1 找到你要点击的位置 2 定位它 这里有讲如何定位 3 复制那个位置 粘贴到元素选择器
  • Pytorch学习笔记(1)第四章 神经网络工具箱nn

    今天学习内容 https github com chenyuntc pytorch book blob master chapter4 E7 A5 9E E7 BB 8F E7 BD 91 E7 BB 9C E5 B7 A5 E5 85 B
  • 账号和权限管理——设置目录和文件的归属(五)

    设置目录和文件的归属 1 chown 命令 需要设置文件或者目录的归属时 主要通过 chown 命令进行 可以只设置属主或属组 也可以同时设置属主 属组 使用 chown 命令的基本格式如下 chown 属主 属组 文件或目录 同时设置属主
  • django入门:Admin管理系统及表单(干货)

    点击上方蓝字关注公众号 码个蛋第310次推文 作者 Kuky xs 博客 https www jianshu com p 8cdf099e974f 前言 django入门 环境及项目搭建 django入门 数据模型 django入门 视图及
  • Anaconda安装虚拟环境下的Jupyter Notebook没有快捷方式怎么办

    Anaconda安装虚拟环境下的Jupyter Notebook没有快捷方式怎么办 今天为了安装tensorflow 在anaconda环境下创建了一个名称为tensorflow虚拟环境 一波操作装完了tensorflow之后 为了在jup

随机推荐

  • 食品行业仓储条码管理系统解决方案

    食品行业总是保持一贯的稳健增势 而且整体行业在产品结构 市场竞争力 运营成本等方面仍有相当的潜力可以发掘 但食品安全问题 消费者口味的不断变化 多变的渠道模式和供应链效率问题 这些都为食品饮料行业建立了一个动荡的充满挑战和机遇的商业环境 而
  • Oracle 数据库升级

    转载来源 Oracle 数据库升级 https mp weixin qq com s LIDIsmeZRRfZmOVtOkeznQ 一 环境准备 本次测试尽量按照生产环境升级进行模拟 故而使用2台主机进行测试 注意 源库为生产环境 linu
  • 【Java编程】JavaSE基础总结(六):多线程

    JavaSE基础总结 六 进程是程序执行的实体 每一个进程都是一个应用程序 比如我们运行QQ 浏览器 LOL 网易云音乐等软件 都有自己的内存空间 CPU 一个核心同时只能处理一件事情 当出现多个进程需要同时运行时 CPU一般通过 时间片轮
  • [精通Objective-C]块(block)

    精通Objective C 块 block 参考书籍 精通Objective C 美 Keith Lee 目录 精通Objective C块block 目录 块的语法 块的词汇范围 块的内存管理 块的使用 使用块为数组排序 使用块的并行编程
  • 让你真正明白cinder与swift、glance的区别

    http www aboutyun com thread 10060 1 1 html 问题导读 1 你认为cinder与swift区别是什么 2 cinder是否存在单点故障 3 cinder是如何发展而来的 在openstack中 我们
  • 计算机辅助绘图考试题,计算机辅助设计绘图考试题(A)(大学期末复习试题).doc...

    教师试做时间出题教师 取题时间审核教研室主任出题单位使用班级考试日期院 部 主任考试成绩期望值印刷份数规定完成时间交教务科印刷日期 学号 姓名 班级 密 封 线 专业 年级 班 学年 第 学期 计算机辅助设计绘图 A 课试卷 题号一二三四五
  • Swagger 的简介和使用

    文章目录 Swagger 的简介和使用 什么是Swagger 简介 Swagger页面 Swagger快速上手 pom xml文件中引入依赖 构建Swagger配置类 Swagger使用 常用注解说明 注解的使用 总结 Swagger 的简
  • Spark jar包加载顺序及冲突解决

    一 spark jar包加载顺序 1 SystemClasspath Spark安装时候提供的依赖包 通常是spark home目录下的jars文件夹 SystemClassPath 2 Spark submit jars 提交的依赖包 U
  • Java-Map集合

    基本使用 public class Demomap public static void main String args Map
  • 关于VMware workstation Player的虚拟网络编辑器没有的情况

    VMware workstation Player 是没有 虚拟网络编辑器的 如果要按照韦东山老师的方法去配置NAT网络 可以再下载VMware workstation pro 尽管不在试用期 依然会给你虚拟网络编辑器的应用安装
  • 光照 (5) 光照贴图

    物体在不同的部件上都有不同的材质属性 1 1 漫反射 允许我们对物体的漫反射分量 以及间接地对环境光分量 它们几乎总是一样的 和镜面光分量有着更精确的控制 漫反射贴图 Diffuse Map 使用一张覆盖物体的图像 让我们能够逐片段索引其独
  • 十大排序算法:快速排序算法

    一 快速排序算法思想或步骤 分解 数组A p r 被划分为两个子数组A p q 1 和A q 1 r 使得A q 为大小居中的数 左侧A p q 1 中的每个元素都小于等于它 而右边A q 1 r 每个元素都大于等于它 解决 通过递归调用快
  • linux shell oracle脚本_分享一个shell脚本--统计Oracle最消耗资源的SQL语句

    概述 This project meant to provide useful scripts for DB maintance and management to make work easier and interesting 今天主要
  • Unity Shader Graphs无法代码动态赋值的问题解决

    起因 给一个材质球更换图片 动态更换了很久 换不上去 解决 Reference unity给的是随机的名字只需要改成自己的名字就可以了 完美解决 不需要下划线 只是自己定义的名字 box EndTarget image material S
  • sqli-labs通关攻略教程六(less26~less28a)

    文章目录 less 26 方法1 方法2 补充知识 less 26a less 27 less 27a less 28 less 28a less 26 方法1 由题目可知 本题绕过了空格和注释 注释符用 1 1或者 00绕过 空白符绕过
  • android intent深入解析

    一 Intent的显示调用 1 intent setClass this OtherActivity class 2 intent setClassName this com zizhu activitys OtherActivity 3
  • Linux chown命令

    Linux Unix 是多人多工操作系统 所有的文件皆有拥有者 利用 chown 将指定文件的拥有者改为指定的用户或组 用户可以是用户名或者用户ID 组可以是组名或者组ID 文件是以空格分开的要改变权限的文件列表 支持通配符 一般来说 这个
  • java解决Exception in thread “main“ java.lang.OutOfMemoryError: GC overhead limit exceeded

    这个就是内存占用超过了限制 解决方案 加载文件的容量太大 这个只能切分文件 使用BufferedInputStream一行行读取 BufferedInputStream bufferedReader new BufferedInputStr
  • 输入三角形的3个边长,a,b,c求出三角形的面积。(C语言)

    代码 define CRT SECURE NO WARNINGS 1 include
  • requestBody注解转化json报错

    RequestBody ResponseBody 注解详解 转 解决方法 不要用modelMap 新建一个hashMap类即可 进来给app写接口比较多 遇到一个bug requestBody会自动往modelMap里加解决办法 清空map