指定响应中的JSON名称

时间:2017-11-10 16:13:06

标签: spring spring-mvc

我希望能够从我的服务器指定JSON响应中使用的名称。

我有以下代码:

@RequestMapping(value = "/accounts/search/forSearchPage", method = RequestMethod.GET)
public ResponseEntity<PagedResources<Resource<Object>>> searchForFeaturedContent() {
    List<Account> nearbyAccounts = accountService.findClosestNearbyAccounts();
    List<Account> onlineAccounts = accountService.findOnlineAccounts();
    Pageable pageable = new PageRequest(0, 10);
    Page<Place> places = placeService.findTop10ByFeaturedTrue(pageable);
    List<Place> placesList = places.getContent();

    List<Object> accountsAndPlaces = new ArrayList<>();
    accountsAndPlaces.addAll(nearbyAccounts);
    accountsAndPlaces.addAll(onlineAccounts);
    accountsAndPlaces.addAll(placesList);

    // Create page out of this list
    Page<Object> pageOfAccountsAndPlaces = new PageImpl<>(accountsAndPlaces, pageable, accountsAndPlaces.size());
    return new ResponseEntity<>(objectPagedAssembler.toResource(pageOfAccountsAndPlaces), HttpStatus.OK);
}

这会返回如下响应:

{
"_embedded" : {
    "places" : [...],
    "accounts" : [...],
    "_links" : {
    "self" : {
        "href" : "http://staging-api.papped.co/accounts/search/forSearchPage"
    }
},
"page" : {
    "size" : 10,
    "totalElements" : 10,
    "totalPages" : 1,
    "number" : 0
}

将所有帐户组合在一起,并将其粘贴在“帐户”名称下。但是,我想将其更改为:

{
"_embedded" : {
    "places" : [...],
    "nearbyAccounts" : [...],
    "onlineAccounts" : [...], // <- See how these have been separated
    "_links" : {
    "self" : {
        "href" : "http://staging-api.papped.co/accounts/search/forSearchPage"
    }
},
"page" : {
    "size" : 10,
    "totalElements" : 10,
    "totalPages" : 1,
    "number" : 0
}

我该怎么做?

2 个答案:

答案 0 :(得分:0)

当您将这两个帐户列表添加到accountsAndPlaces列表中时,您无意中将两个帐户列表连接在一起。

替换:

List<Account> nearbyAccounts = accountService.findClosestNearbyAccounts();
List<Account> onlineAccounts = accountService.findOnlineAccounts();

使用:

List<NearByAccounts> nearbyAccounts = accountService.findClosestNearbyAccounts();
List<OnlineAccounts> onlineAccounts = accountService.findOnlineAccounts();

您还必须创建两个新类:

public class NearByAccount extends Account {}

public class OnlineAccounts extends Account {}

答案 1 :(得分:0)

一种简单的方法是声明一个将按预期序列化的类。

public class MeaningfulNameHere {
    Collection<Account> nearbyAccount;
    Collection<Account> onlineAccount;
    Collection<Place> places;

    /* constructors and getters */
}

不是放置对象列表,而是返回给定类的实例。根据您的序列化库,您可能需要在新类型上添加一些anotations。最有可能的是,你的是杰克逊,而且会像它一样工作。