使用spring-hateoas反序列化JSON(链接+嵌入式容器)的便捷方法是什么?

V. *_*kyi 6 json hateoas jackson spring-hateoas json-deserialization

同事!

我们希望将Rest Client写入遵循HATEOAS原则的服务.所以我们有以下HAL + JSON表示,我们想使用spring-hateoas反序列化它:

{
    "id": "1",
    "title": "album title",
    "artistId": "1",
    "stockLevel": 2,
    "_links": {
        "self": {"href": "http://localhost:8080/rest/albums/1"},
        "artist": {"href": "http://localhost:8080/rest/artist/1"}
    },
    "_embedded": {
        "albums": [{ //can be array or object
            "id": "1",
            "title": "album title",
            "artistId": "1",
            "stockLevel": 2,
            "_links": {
                "self": {"href": "http://localhost:8080/rest/albums/1"}
            }
        }],
        "artist": { //can be array or object
            "id": "1",
            "name": "artist name",
            "_links": {
                "self": {"href": "http://localhost:8080/rest/artist/1"}
            }
        } //.... 
    }
}
Run Code Online (Sandbox Code Playgroud)

我们期望这样的java对象:

HalResource {
    Resource<Album> //entity 
    List<Link> // _links
    List<Resource<BaseEntity>>{ //_embedded
        Resource<Album>
        Resource<Artist>
         ....
    } 
}
Run Code Online (Sandbox Code Playgroud)

所以我们有嵌入式(资源列表)和实体(单一资源)的自定义资源表示:

@XmlRootElement(name = "resource")
public class HalResource<EntityType, EmbeddedType> extends Resources<EmbeddedType> {

    @JsonUnwrapped
    private EntityType entity;

    public HalResource() {
    }

    public HalResource(Iterable<EmbeddedType> content, Link... links) {
        super(content, links);
    }

    public EntityType getEntity() {
        return entity;
    }

    public void setEntity(EntityType entity) {
        this.entity = entity;
    }
}
Run Code Online (Sandbox Code Playgroud)

DTO课程:

public abstract class BaseEntity{}

@XmlRootElement(name = "album")
public class Album extends BaseEntity {  
    private String id;
    private String title;
    private String artistId;
    private int stockLevel;

    // getters and setters...
}

@XmlRootElement(name = "artist")
public class Artist extends BaseEntity {
    private String id;
    private String name;

    // getters and setters...
}
Run Code Online (Sandbox Code Playgroud)

我们希望得到类似这样的东西,其中Entity将是Artist或Album,但HalResourcesDeserializer返回Resource.class并带有null内容.

    HalResource<Album, Resource<Entity>> resources = 
    restClient.getRootTarget().path("albums/1").queryParam("embedded", true).request().accept("application/hal+json")
    .get(new GenericType<HalResource<Album, Resource<Entity>>>() {});
Run Code Online (Sandbox Code Playgroud)

通过使用@JsonTypeInfo@JsonSubTypes anotations,我们成功地反序列化了我们的JSON(您可以在github上看到示例),但我们不希望在DTO和JSON格式中有一些额外的类型fild和anotattions.

我们看到一个解决方案是创建一个可以处理它的自定义反序列化器.

所以问题是:使用spring-hateoas反序列化我们的JSON(链接+嵌入式容器)的便捷方法什么?

我们使用spring-hateoas 0.16v(但我们尝试了0.19v)和glassfish jersey 2.22.1

谢谢!