2014-02-06 62 views
1

現在我正在使用Jackson JSON處理器從對象中返回JSON,但是如果有更好的方法來執行此操作,我很樂意提供建議。目標是根據方法/ url定義哪些屬性將包含在JSON響應中。根據彈簧控制器配置JSON輸出方法

例子:

型號

class League { 
    String name; 
    List<Team> teams; 
    ... 
} 

class Team { 
    String name; 
    String nation; 
    int points; 
    List<Player> players; 
    ... 
} 

class Player { 
    String name; 
    Team team; 
    ... 
} 

控制器

@Controller 
public class LeagueController { 

    @RequestMapping(value="/league",method = RequestMethod.GET) 
    public @ResponseBody 
    League getLeague() { 
    //return the teams shouldn't include the player list 
    } 

    @RequestMapping(value="/team/{id}",method = RequestMethod.GET) 
    public @ResponseBody 
    Team getTeamById(Long id) { 
    //return team including the players but if possibe use the teamname inside the JSON 
    //instead of the entire back reference (which producess an infinite loop. 
    } 
} 

我看着在傑克遜的註解,但它並沒有得到我任何進一步或提出新的問題。

+0

我認爲你要找的是一個傑克遜自定義串行器。 – CodeChimp

+0

請檢查我的答案,並讓我知道尋求幫助。 –

回答

1

你可以有JSON定製註釋忽略的字段,忽略null,在你java classJSON轉換爲忽略empty String

@JsonIgnore 
private KeyValueCollection userData; 

private String participants = ""; 

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) 
private boolean garbageEligible; 


@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) 
private String interactionType ; 

@JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY) 
private LinkedList<InteractionInfo> interactions; 

我已經使用了jackson 1.9

希望這會有所幫助。

+0

感謝您的回覆,我會在接下來的幾天嘗試,並回來標記您的答案或其他問題。 – KenavR

+0

welcome.Then請讓我知道你發生了什麼事? –