3

私の URI は http://localhost:8080/context/my-objects/search/findByCode?code=foo です。

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。

4

1 に答える 1

5

私は解決策を見つけました。まず、Resources クラスを作成します。

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 メディア タイプをサポートする必要があります。

またはトラバーソンで:

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) {}

POJO MyObject を ResourceSupport クラスで拡張したくない場合は、Resources クラスに Resource を指定する必要があります。

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

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

(リンクが必要ない場合は、type パラメーターを MyObject にすることもできます)。

于 2015-02-09T09:54:07.263 に答える