0

我有两节课:

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

我怎样才能让杰克逊只输出团队的名称而不是完整的对象?

4

2 回答 2

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

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

于 2013-03-03T05:48:37.157 回答
0

排除Team对象的所有属性,除了nameusing :@JsonIgnoreProperties

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

这样杰克逊将只序列化 JSON 中的团队名称。

于 2013-03-03T00:05:22.917 回答