java类动态移除字段_如何从json响应中动态删除字段?

我正在使用spring创建一个宁静的api,到目前为止,我的问题是如何动态建模响应的字段?

那就是我正在使用的控制器:

@Controller

public class AlbumController {

@Autowired

private MusicService musicService;

@RequestMapping(value = "/albums", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)

@ResponseBody

public Collection> getAllAlbums() {

Collection albums = musicService.getAllAlbums();

List> resources = new ArrayList>();

for (Album album : albums) {

resources.add(this.getAlbumResource(album));

}

return resources;

}

@RequestMapping(value = "/album/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)

@ResponseBody

public Resource getAlbum(@PathVariable(value = "id") String id) {

Album album = musicService.getAlbum(id);

return getAlbumResource(album);

}

private Resource getAlbumResource(Album album) {

Resource resource = new Resource(album);

// Link to Album

resource.add(linkTo(methodOn(AlbumController.class).getAlbum(album.getId())).withSelfRel());

// Link to Artist

resource.add(linkTo(methodOn(ArtistController.class).getArtist(album.getArtist().getId())).withRel("artist"));

// Option to purchase Album

if (album.getStockLevel() > 0) {

resource.add(linkTo(methodOn(AlbumController.class).purchaseAlbum(album.getId())).withRel("album.purchase"));

}

return resource;

}

@RequestMapping(value = "/album/purchase/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)

@ResponseBody

public Resource purchaseAlbum(@PathVariable(value = "id") String id) {

Album a = musicService.getAlbum(id);

a.setStockLevel(a.getStockLevel() - 1);

Resource resource = new Resource(a);

resource.add(linkTo(methodOn(AlbumController.class).getAlbum(id)).withSelfRel());

return resource;

}

}

和模型:

public class Album {

private final String id;

private final String title;

private final Artist artist;

private int stockLevel;

public Album(final String id, final String title, final Artist artist, int stockLevel) {

this.id = id;

this.title = title;

this.artist = artist;

this.stockLevel = stockLevel;

}

public String getId() {

return id;

}

public String getTitle() {

return title;

}

public Artist getArtist() {

return artist;

}

public int getStockLevel() {

return stockLevel;

}

public void setStockLevel(int stockLevel) {

this.stockLevel = stockLevel;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值