【问题标题】:Spring Rest JSON BindingSpring Rest JSON 绑定
【发布时间】:2011-08-03 05:18:35
【问题描述】:

我正在尝试使用 Spring 创建一个 Restful 服务。

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

客户端发送内容类型为“application/json”的 JSON 对象。但我收到错误“HTTP/1.1 415 Unsupported Media Type”。

..即使客户端发送了一个空的“{}”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/>

为此苦苦挣扎了一段时间。我们将不胜感激!

【问题讨论】:

    标签: java json spring rest jackson


    【解决方案1】:

    确保您的类路径中有 Jackson 库,如果您使用的是 maven,请在 pom.xml 中定义以下内容:

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-core-asl</artifactId>
        <version>1.7.5</version>
        <scope>compile</scope>
     </dependency>
     <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.7.5</version>
        <scope>compile</scope>
     </dependency>
    

    【讨论】:

      【解决方案2】:

      这可能不是主要问题,但是如果您的 UserContext bean 只有私有字段,它就不能按原样工作。有多种方法可以解决这个问题;从公开字段到为每个字段添加@JsonProperty,或者只是更改杰克逊用于检测属性字段的最低可见性(@JsonAutoDetect 注释)。

      但是对于空 JSON,这应该不会产生问题;如果出现问题,您应该会看到不同类型的错误/异常(我假设)。

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-06-26
          • 1970-01-01
          • 2011-05-25
          • 2015-09-01
          • 2011-08-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多