使用Jackson和Spring修改@ManyToOne关联的JSon响应

时间:2013-03-02 21:48:12

标签: json spring jackson

我有两个班级:

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",...

我如何指出杰克逊只输出团队名称而不是完整的对象?

2 个答案:

答案 0 :(得分: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",...

但可能需要额外处理反序列化。

答案 1 :(得分:0)

使用以下内容排除除Team以外的name对象的所有属性:@JsonIgnoreProperties

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

因此杰克逊将仅在JSON中序列化团队名称。