Search code examples
jsonforeign-keysjacksondropwizardjackson-modules

How to resolve foreign keys from JSON object with Jackson


In a book library system with Dropwizard (with Jackson and Hibernate), there are the following classes:

@Entity
@Table(name="author")
public class Author {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(name="name")
    private string name;
    // some more properties
}

@Entity
@Table(name="book")
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(name="title")
    private string title;
    // some more properties
}

@POST
public void addBook(Book book) {
    ...
}

To add a book, the book's title and the id of the author should be send as a json object.

{"title": "Harry Potter", "author": "123"}

However, it looks like Jackson is not capable of getting the author out of the given author id.

Error 400 Can not instantiate value of type [simple type] from Integral number; no single-int-arg constructor/factory method (through reference chain)

Is there a way to configure the mapping from the JSON of the request to a book object and from the authorId to the author, without creating a temporary object like

class TempBook { string title; long authorId; }

Solution

  • Your Book entity does not have a "author" property. So Jackson won't be able to marshall/unmarshall your JSON to/from an actual Book instance. A way I can think of is through setter/getters helper methods, something like this:

    @OneToOne private Author authorEntity;
    public void setAuthor(String author) { this.autorEntity = new Author(author);}
    

    But you will have to consider adding a proper getter for the marshalling process, and using the @JsonIgnoreProperties annotation for the authorEntity property.

    Hope this helps.