加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – Spring Rest JSON绑定

发布时间:2020-12-15 08:39:34 所属栏目:Java 来源:网络整理
导读:我正在尝试用 Spring创建Restful服务. 方法通过参数接受“UserContext”对象,即@RequestBody. 客户端使用内容类型“application / json”发送JSON对象.但我收到错误“HTTP / 1.1 415不支持的媒体类型”. ..甚至当客户端发送一个空的“{}”JSON对象时. 我的控
我正在尝试用 Spring创建Restful服务.

方法通过参数接受“UserContext”对象,即@RequestBody.

客户端使用内容类型“application / json”发送JSON对象.但我收到错误“HTTP / 1.1 415不支持的媒体类型”.

..甚至当客户端发送一个空的“{}”JSON对象时.

我的控制器:

@Controller
@RequestMapping(value = "/entityService")
class RestfulEntityService {

  @Resource
  private EntityService entityService;

  @ResponseBody
  @RequestMapping(value = "/getListOfEntities",method = RequestMethod.POST)
  public List<Entity> getListOfEntities(@RequestBody UserContext userContext) {
    System.out.println(userContext);
    return null;
  }
}

UserContext.java

public class UserContext {

    private Long userId;

    private String userName;

    private UserAddress userAddress;

    private CustomerInfo customerInfo;

}

应用背景:

<bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller"/>
  <bean id="xmlMessageConverter"
        class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
    <constructor-arg ref="xstreamMarshaller"/>
    <property name="supportedMediaTypes" value="application/xml"/>
  </bean>

  <bean id="jsonHttpMessageConverter"
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    <property name="supportedMediaTypes" value="application/json"/>
  </bean>

  <bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
      <util:list id="beanList">
        <ref bean="xmlMessageConverter" />
        <ref bean="jsonHttpMessageConverter"/>
      </util:list>
    </property>
  </bean>

  <mvc:annotation-driven/>

苦苦挣扎了一会儿.帮助将不胜感激!

解决方法

根据我在 mvc-showcase的messageconverter示例中看到的内容,在application / json请求中尝试使用Accept标头

这是一个相关的问题:use spring mvc3 @ResponseBody had 415 Unsupported Media Type why?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读