2015-02-06 58 views
2

我的URI是 http://localhost:8080/context/my-objects/search/findByCode?code=foo春天引導數據休息findby traverson到java對象

JSON響應:

{ 
    "_embedded" : { 
    "my-objects" : [ { 
     "code" : "foo", 
     "description" : "foo description", 
     "_links" : { 
     "self" : { 
      "href" : "http://localhost:8080/context/my-objects/34" 
     } 
     } 
    } ] 
    } 
} 

我怎樣才能用Traverson或RestTemplate一個java的MyObject?

import org.springframework.hateoas.ResourceSupport; 

public class MyObject extends ResourceSupport{ 

    private String code; 

    private String description; 

    public String getDescription() { 
     return description; 
    } 

    public void setDescription(final String description) { 
     this.description = description; 
    } 

    public String getCode() { 
     return code; 
    } 

    public void setCode(final String code) { 
     this.code = code; 
    } 

} 

這是我的模板。我也嘗試了一個默認的。

{ 
ObjectMapper mapper = new ObjectMapper(); 
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 
mapper.registerModule(new Jackson2HalModule()); 

MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); 
converter.setSupportedMediaTypes(MediaType.parseMediaTypes("application/hal+json")); 
converter.setObjectMapper(mapper); 

RestTemplate template = new RestTemplate(Collections.<HttpMessageConverter<?>> singletonList(converter)); 

} 

Thx提前。

回答

5

我找到了解決方案。首先,創建一個類資源:

import org.springframework.hateoas.Resources; 

public class MyObjects extends Resources<MyObject> { } 

然後是簡單的:

MyObjects myObjects = template.getForObject("http://localhost:8080/context/my-objects/search/findByCode?code=foo", MyObjects.class); 

注意:模板應該支持HAL + json的媒體類型。

或者與Traverson:

import org.springframework.hateoas.Resource; 
import org.springframework.hateoas.Resources; 

public class MyObjects extends Resources<Resource<MyObject>> { } 

(如果你不:

import org.springframework.hateoas.MediaTypes; 
import org.springframework.hateoas.client.Traverson; 

Traverson traverson; 
try{ 
    traverson = new Traverson(new URI("http://localhost:8080/context"), MediaTypes.HAL_JSON); 
    Map<String, Object> parameters = new HashMap<String, Object>(); 
    parameters.put("code", "foo"); 

    MyObjects myObjects = traverson.follow("my-objects", "search", "findByCode").withTemplateParameters(
       parameters).toObject(MyObjects.class); 
} catch (URISyntaxException e) {} 

如果你不想與擴展類ResourceSupport您POJO myObject的,你的資源類應與資源類型需要鏈接的類型參數可能再次是MyObject)。

0

這是你要找的答案嗎?

MyObject[] response = new RestTemplate().getForObject("http://localhost:8080/context/my-objects/search/findByCode?code=foo", MyObject[].class); 
+0

我收到一個異常:無法讀取JSON:無法將START_OBJECT令牌的MyObject []實例反序列化 – user1648825 2015-02-09 08:59:44