消耗HATEOAS资源

时间:2014-09-05 21:06:29

标签: spring spring-mvc jackson hateoas spring-hateoas

我有一个简单的 HATEOAS 提供程序,使用 Spring 构建,为我提供以下资源:

{
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/employees{?page,size,sort}",
      "templated" : true
    },
    "search" : {
      "href" : "http://localhost:8080/employees/search"
    }
  },
  "_embedded" : {
    "employees" : [ {
      "id" : "5400d5152f5243f1988c649b",
      "name" : "Some Employee",
      "location" : [ 0.0, 0.0 ],
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/employees/5400d5152f5243f1988c649b"
        }
      }
    }, {
      "id" : "5400d5162f5243f1988c649c",
      "name" : "Some Employee",
      "location" : [ 0.0, 0.0 ],
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/employees/5400d5162f5243f1988c649c"
        }
      }
    }, {
      "id" : "5400d5172f5243f1988c649d",
      "name" : "Some Employee",
      "location" : [ 0.0, 0.0 ],
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/employees/5400d5172f5243f1988c649d"
        }
      }
    } ]
  },
  "page" : {
    "size" : 20,
    "totalElements" : 3,
    "totalPages" : 1,
    "number" : 0
  }
}

在一个单独的Spring客户端中,我尝试使用此资源但无效:

@RequestMapping("/employees")
public String getAllEmployees() {

    try {
        ResponseEntity<Resource> responseEntity = restTemplate.getForEntity(RESOURCE_URI, Resource.class);
    }
    catch(Exception e) {
        e.printStackTrace();
    }
    return null;
}

杰克逊2.0继续抱怨:

org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Unrecognized field "page" (class org.springframework.hateoas.Resource), not marked as ignorable (2 known properties: "content", "links"])
 at [Source: org.apache.http.conn.EofSensorInputStream@743a4ace; line: 19, column: 13] (through reference chain: org.springframework.hateoas.Resource["page"]); nested exception is com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "page" (class org.springframework.hateoas.Resource), not marked as ignorable (2 known properties: "content", "links"])
 at [Source: org.apache.http.conn.EofSensorInputStream@743a4ace; line: 19, column: 13] (through reference chain: org.springframework.hateoas.Resource["page"])
    at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readJavaType(MappingJackson2HttpMessageConverter.java:216)
    at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.read(MappingJackson2HttpMessageConverter.java:208)
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:95)
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:784)
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:769)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:549)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:502)
    at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:264)
    at com.provider.spring.controller.EmployeeController.getAllEmployees(EmployeeController.java:34)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:175)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:446)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:434)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:534)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "page" (class org.springframework.hateoas.Resource), not marked as ignorable (2 known properties: "content", "links"])
 at [Source: org.apache.http.conn.EofSensorInputStream@743a4ace; line: 19, column: 13] (through reference chain: org.springframework.hateoas.Resource["page"])
    at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:51)
    at com.fasterxml.jackson.databind.DeserializationContext.reportUnknownProperty(DeserializationContext.java:731)
    at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:915)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1298)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1276)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:243)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:118)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3051)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2206)
    at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readJavaType(MappingJackson2HttpMessageConverter.java:213)
    ... 44 more
Sep 05, 2014 3:54:08 PM org.apache.catalina.core.ApplicationDispatcher invoke
WARNING: Servlet jsp is currently unavailable

对于calrity,这是我的Resource对象: https://gist.github.com/Xerosigma/02041fdc0849a651dcbf

我缺少什么?

3 个答案:

答案 0 :(得分:2)

默认的jackson映射器配置为在json对象上无法识别的字段上失败。您需要使用mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

配置映射器

这是一个Spring配置示例:

package com.pkg.mine;

import org.codehaus.jackson.map.AnnotationIntrospector;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.introspect.JacksonAnnotationIntrospector;
import org.codehaus.jackson.xc.JaxbAnnotationIntrospector;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.List;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.pkg.mine")
public class ServerConfig extends WebMvcConfigurerAdapter {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //We handle both incoming JSON, and XML
        final AnnotationIntrospector jsonInspector = new JacksonAnnotationIntrospector();
        final AnnotationIntrospector xmlInspector = new JaxbAnnotationIntrospector();
        final AnnotationIntrospector pair = 
              new AnnotationIntrospector.Pair(jsonInspector, xmlInspector);

        final ObjectMapper om = new ObjectMapper();
        //Don't fail if additional fields in incoming JSON, just ignore
        om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //Don't fail on incoming JSON missing fields
        om.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
        om.setAnnotationIntrospector(pair);

        final MappingJacksonHttpMessageConverter converter = 
                new MappingJacksonHttpMessageConverter();
        converter.setObjectMapper(om);
        converters.add(converter);
    }
}

答案 1 :(得分:1)

使用

    ResponseEntity<PagedResources<EmployeeResource>> responseEntity = restTemplate.exchange("URI", HttpMethod.GET, null, new ParameterizedTypeReference<PagedResources<EmployeeResource>>(){});

其中EmployeeResource是一个资源类。获得员工

  

responseEntity.getBody()。getContent

上面的代码片段将返回EmployeeResource的集合

答案 2 :(得分:0)

您的类Resource似乎没有名为page的字段,因此解析器无法处理此json对象:

"page" : {
    "size" : 20,
    "totalElements" : 3,
    "totalPages" : 1,
    "number" : 0
}

您可以尝试:

public class Page {

    private int size;

    private int totalElements;

    private int totalPages;

    private int number;

    // Getters and Setters...
}

并在您的班级Resource中:

public class Resource<T> extends ResourceSupport {

    private final T content;

    private Page page;

    ...
}