2013-03-02 42 views
0

@ManyToOne協會我有兩類:修改JSON性反應的使用傑克遜和Spring

public class Team { 
    private Long id; 
    private String name; 
     ... 
} 
public class Event { 
    private Long id; 

    @ManyToOne 
    private Team homeTeam; 

    @ManyToOne 
    private Team guestTeam; 
... 
} 

控制器:

public @ResponseBody List<Event> getAll() {... 
} 

現在我有JSON:

[{"id":1,"homeTeam":{"id":2,"name":"Golden State"},"guestTeam":{"id":1,"name":"Philadelphia"},... 

我想要什麼:

[{"id":1,"homeTeam":"Golden State","guestTeam":"Philadelphia",... 

我怎麼可以指出Jackson只輸出Team的名字而不是完整的Object?

回答

2

Benoit的答案不會產生所需形式的JSON,它會產生這樣的:

[{"id":1,"homeTeam":{"name":"Golden State"},"guestTeam":{"name":"Philadelphia"},... 

相反,你需要做的是讓你的Team類是這個樣子的:

public class Team { 
    private Long id; 
    private String name; 

    public Long getId() { 
     return id; 
    } 

    @JsonValue 
    public String getName() { 
     return name; 
    } 

    ... 
} 

這將產生所需的JSON:

[{"id":1,"homeTeam":"Golden State","guestTeam":"Philadelphia",... 

但是可能需要額外處理反序列化。

+0

工作正常。謝謝 – Escander 2013-03-03 11:31:54

0

排除除了使用nameTeam對象的所有屬性:@JsonIgnoreProperties

@JsonIgnoreProperties 
public String getPropertyToExclude() { 
    return propertyToExclude; 
} 

所以,傑克遜將在JSON序列只有團隊的名字。