0

I'm having trouble deserializing JSON arrays to optional lists and adding them to MongoDB using morphia. Instead of adding the actual elements of the array to Mongo, the size of the array is added. See code below...

BookWrapper Class

public class BookWrapper {

    private List<Book> books;

    public List<Book> getBooks() {
        return books;
    }

    public void setBooks(List<Book> books) {
        this.books = books;
    }
}

Book Class

@Entity("Book")
public class Book {

    private String name;
    private Optional<List<String>> authors = Optional.empty();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Optional<List<String>> getAuthors() {
        return authors;
    }

    public void setAuthors(Optional<List<String>> authors) {
        this.authors = authors;
    }

}

Upload Books Method

public void uploadBook() throws IOException {
        File file = new File("data/book.json");
        mapper.registerModule(new Jdk8Module());
        BookWrapper wrapper = mapper.readValue(file, BookWrapper.class);
        List<Book> books = wrapper.getBooks();
        for(Book book : books) {
            db.save(book);
        }
}

book.json File

{
    "books" : [
        {
            "name": "Best Book Ever",
            "authors": ["John Smith", "Mike Apple"]
        },
        {
            "name": "Tale of Legends",
            "authors": ["Anne Lumo", "Andre John"]
        }
    ]
}

Mongo Inserted Document no elements, only the size of the array!

Captain Jack Sparrow
  • 971
  • 1
  • 11
  • 28
  • I've been seeing that Java Optionals aren't serializable. Could this be the reason why my code isn't behaving as expected? – ineedhelppls May 06 '20 at 15:11

1 Answers1

1

Using Optional on fields is a misuse of the type and isn't recommend. Brian Goetz himself has recommended against it. Certainly if you're using Morphia to persist those entities, there's no support for Optional fields at all and so it's not surprising you're getting odd behavior. Your entity should just have List<String> for authors.

evanchooly
  • 6,102
  • 1
  • 16
  • 23
  • I saw a bunch of people saying this as well and actually changed everything to mimmic the first answer from this [post](https://stackoverflow.com/questions/35033225/jackson-deserialize-missing-properties-as-empty-optional) Everything seems to work fine now, thanks! – ineedhelppls May 06 '20 at 19:40