Spring REST: HttpMediaTypeNotSupportedException: Тип контента 'application/json; charset = UTF-8' - программирование
Подтвердить что ты не робот

Spring REST: HttpMediaTypeNotSupportedException: Тип контента 'application/json; charset = UTF-8'

Я получаю вышеуказанную ошибку из-за проблемы с Джексоном, пытающейся десериализовать мой POJO.

Я отлаживал код, и он возвращает false внутри объекта Jackson ObjectMapper:

public boolean canRead(Type type, Class<?> contextClass, MediaType mediaType) {
    JavaType javaType = getJavaType(type, contextClass);
    return (this.objectMapper.canDeserialize(javaType) && canRead(mediaType));
}

this.objectMapper.canDeserialize(javaType) возвращает false, что вызывает ошибку

Мой контроллер выглядит следующим образом:

@Controller
public class CancelController {
    @Autowired
    private CancelService cancelService;

    @RequestMapping( value="/thing/cancel", method=RequestMethod.POST, consumes="application/json" )
    public @ResponseBody CancelThingResponseDTO cancelThing(@RequestBody CancelRequestDTO cancelThingRequest) {
        return cancelService.cancelThing(cancelThingRequest);
    }

My CancelRequestDTO реализует Serializable:

public class CancelRequestDTO implements Serializable{
  /**
   * Default serialization ID
   */
  private static final long serialVersionUID = 1L;
  /**
   * Reason code associated with the request
   */
  private final String reasonCode;
  /**
   * Identifier of the entity associated with the request
   */
  private final EntityIdentifier entityIdentifier;

  /**
   * Default constructor
   *
   * @param reasonCode Reason code associated with the request
   * @param entityIdentifier Identifier of the entity associated with the request
   */
  public CancelRequestDTO(String reasonCode, EntityIdentifier entityIdentifier) {
    super();
    this.reasonCode = reasonCode;
    this.entityIdentifier = entityIdentifier;
  }
  /**
   * @return Returns the reasonCode.
   */
  public String getReasonCode() {
    return reasonCode;
  }
  /**
   * @return Returns the entityIdentifier.
   */
  public EntityIdentifier getEntityIdentifier() {
    return entityIdentifier;
  }
}

Моя конфигурация Spring такова:

<!-- DispatcherServlet Context: defines this servlet request-processing
    infrastructure -->

<!-- Enables the Spring MVC @Controller programming model -->
<mvc:annotation-driven />

<!-- Scan for stereotype annotations -->
<context:component-scan base-package="com.cancel.web.controller" />

<bean id="viewNameTranslator"
    class="org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator" />

<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />





<bean id="jsonView"
    class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" >
    <property name="contentType" value="application/json;charset=UTF-8"/>
    </bean>

<!-- Register JSON Converter for RESTful Web Service -->
<bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <bean
                class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
            </bean>
        </list>
    </property>
</bean>

Кто-нибудь знает, что может вызвать эту проблему десериализации?

Спасибо

4b9b3361

Ответ 1

Причиненный моим DTO, не имеющий конструктор по умолчанию с сеттерами! Так выглядит неточное исключение из Джексона

Ответ 2

Для тех, кто все еще сталкивается с этой проблемой, вы не можете иметь два @JsonBackReference в одном классе, добавьте значение в одну из ссылок, подобную этой @JsonBackReference(value = "secondParent"), и добавьте то же значение к @JsonManagedReference(value ="secondParent") в родительский класс.

Ответ 3

Я всегда делал это с помощью ContentNegotiationViewResolver. Похоже, что он не понимает тип контента, который вы передаете. Это конфигурация, которую я обычно использую для выполнения того, что вы пытаетесь сделать:

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <property name="order" value="1" />
    <property name="contentNegotiationManager">
        <bean class="org.springframework.web.accept.ContentNegotiationManager">
            <constructor-arg>
                <bean class="org.springframework.web.accept.PathExtensionContentNegotiationStrategy">
                    <constructor-arg>
                        <map>
                            <entry key="json" value="application/json" />
                            <entry key="xml" value="application/xml" />
                        </map>
                    </constructor-arg>
                </bean>
            </constructor-arg>
        </bean>
    </property>

    <property name="defaultViews">
        <list>
            <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
            <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
                <constructor-arg>
                    <bean class="org.springframework.oxm.xstream.XStreamMarshaller">
                        <property name="autodetectAnnotations" value="true" />
                    </bean>
                </constructor-arg>
            </bean>
        </list>
    </property>
</bean>

Это видео проходит через то, что вы пытаетесь сделать с использованием службы через jQuery в пользовательском интерфейсе:

http://pluralsight.com/training/Courses/TableOfContents/springmvc-intro