Juan Diego
Juan Diego

Reputation: 863

JAX-RS - toString() of associated object in JSON property value

I have these two Java classes

public class Artist {
    @Id
    private Integer id;
    private String name;
    private Short birthYear;
    @JsonIgnore                                                // This is Jackson
    @OneToMany(mappedBy = "artist", fetch = FetchType.EAGER)   // This is JPA
    private List<Album> albums = new ArrayList<Album>();
    . . .
    @Override
    public String toString() {
        return name;
    }
}

public class Album {
    @Id
    private Integer id;
    private String name;
    private Short releaseYear;
    @ManyToOne                                                 // This is JPA
    private Artist artist;
}

Now, what I want is when I produce JSON objects of the Album class it returns something like this:

{
    id : 2012000587,
    name : 'Escultura',
    releaseYear : '2012',
    artist : 'Guaco'
}

Right now it outputs:

{
    id : 2012000587,
    name : 'Escultura',
    releaseYear : '2012',
    artist : {
        id : 2044452000,
        name : 'Guaco',
        birthYear : 1987
    }
}

I want to avoid at any cost using custom serializers for this matter.

How can I do that?

Upvotes: 0

Views: 831

Answers (1)

Alexey Gavrilov
Alexey Gavrilov

Reputation: 10853

Try to add a getter for name property and annotation it with a @JsonValue annotation.

public class Artist {
    private String name;
    ...
    @JsonValue
    public String getName() { return name; }
}

Here is the link to the Jackson Wiki page for reference.

Upvotes: 1

Related Questions