我正在尝试添加 HATEOAS 链接Resource<>
,同时还使用@JsonView
. 但是,我不知道如何将链接添加到嵌套对象。
在Github上的项目中,我扩展了这个项目(添加打开的拉取请求以使其在没有嵌套资源的情况下工作),添加具有嵌套User
.
访问~/characters/resource-filtered
路由时,预计嵌套的User
“播放器”会出现firstNm
andbioDetails
字段,并带有 Spring 生成的指向自身的链接,但没有userId
andlastNm
字段。
我的过滤工作正常,但我找不到符合ResourceAssembler
范式的嵌套资源示例。似乎有必要使用 aResourceAssembler
来进行@JsonView
工作。
任何协调这两个概念的帮助将不胜感激。如果您可以完全破解它,请考虑向我发送拉取请求。
用户.java
//package and imports
...
public class User implements Serializable {
@JsonView(UserView.Detail.class)
private Long userId;
@JsonView({ UserView.Summary.class, CharacterView.Summary.class })
private String bioDetails;
@JsonView({ UserView.Summary.class, CharacterView.Summary.class })
private String firstNm;
@JsonView({ UserView.Detail.class, CharacterView.Detail.class })
private String lastNm;
public User(Long userId, String firstNm, String lastNm) {
this.userId = userId;
this.firstNm = firstNm;
this.lastNm = lastNm;
}
public User(Long userId) {
this.userId = userId;
}
...
// getters and setters
...
}
CharacterModel.java
//package and imports
...
@Entity
public class CharacterModel implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@JsonView(CharacterView.Summary.class)
private Long characterId;
@JsonView(CharacterView.Detail.class)
private String biography;
@JsonView(CharacterView.Summary.class)
private String name;
@JsonView(CharacterView.Summary.class)
private User player;
public CharacterModel(Long characterId, String name, String biography, User player) {
this.characterId = characterId;
this.name = name;
this.biography = biography;
this.player = player;
}
public CharacterModel(Long characterId) {
this.characterId = characterId;
}
...
// getters and setters
...
}
CharacterController.java
//package and imports
...
@RestController
@RequestMapping("/characters")
public class CharacterController {
@Autowired
private CharacterResourceAssembler characterResourceAssembler;
...
@JsonView(CharacterView.Summary.class)
@RequestMapping(value = "/resource-filtered", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public Resource<CharacterModel> getFilteredCharacterWithResource() {
CharacterModel model = new CharacterModel(1L, "TEST NAME", "TEST BIOGRAPHY", new User(1L, "Fred", "Flintstone"));
return characterResourceAssembler.toResource(model);
}
...
}
CharacterResourceAssembler.java
//package and imports
...
@Component
public class CharacterResourceAssembler implements ResourceAssembler<CharacterModel, Resource<CharacterModel>>{
@Override
public Resource<CharacterModel> toResource(CharacterModel user) {
Resource<CharacterModel> resource = new Resource<CharacterModel>(user);
resource.add(linkTo(CharacterController.class).withSelfRel());
return resource;
}
}