SPRING-HATEOAS + RestTemplate:使用链接实体创建资源?

时间:2014-06-25 16:42:21

标签: spring-hateoas

如何使用与现有实体的一对一关系创建资源?以论坛用户的简单情况为例。我们有两个可以彼此独立存在的顶级资源:User&题。如果你要按字面意思发布你的JSON,你会发送类似的东西:

POST /api/users
{name: "John Doe", "email": "jdoe@example.com"}

并取回位置标题:http://example.com/api/users/1

然后

POST /api/questions
{"author": "http://example.com/api/users/1", "title": "How to do this?", "text": "I don't know how to do this..."}

使用RestTemplate我很想做:

Question q = new Question();
q.author = somePreviouslyCreatedUSerReference;
q...

template.getForLocation("/api/questions", q);

但是你得到的是以下错误,因为反序列化器期待引用。有很多文档可以用来消耗琐碎的REST端点,但在实际创建真实世界资源方面却非常稀疏。


Caused by: com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: com.example.model.Question["author"])
    at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:232)
    at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:197)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.wrapAndThrow(BeanDeserializerBase.java:1420)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:244)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:118)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2993)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2158)
    at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readJavaType(MappingJackson2HttpMessageConverter.java:225)
    ... 39 common frames omitted
Caused by: java.lang.NullPointerException: null
    at java.net.URI$Parser.parse(URI.java:3023)
    at java.net.URI.<init>(URI.java:595)
    at java.net.URI.create(URI.java:857)
    at org.springframework.data.rest.webmvc.json.PersistentEntityJackson2Module$UriStringDeserializer.deserialize(PersistentEntityJackson2Module.java:359)
    at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:525)
    at com.fasterxml.jackson.databind.deser.impl.FieldProperty.deserializeAndSet(FieldProperty.java:106)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:242)
    ... 43 common frames omitted

0 个答案:

没有答案