jasminb / jsonapi-converter

JSONAPI-Converter is a Java/Android library that provides support for working with JSONAPI spec
Apache License 2.0
273 stars 81 forks source link

Difficulty Serialising a List of objects #191

Closed dementiacs closed 6 years ago

dementiacs commented 6 years ago

Consider this snippet.

List<Fault> listOfFaults = ....
JSONAPIDocument<List<Fault>> document = new JSONAPIDocument<>(listOfFaults);

How do I then serialise that into a String?

when I try

bytes = converter.writeDocument(document);

I get an exception

com.fasterxml.jackson.databind.node.ArrayNode cannot be cast to com.fasterxml.jackson.databind.node.ObjectNode

What am I doing wrong?

Fault itself is a simple class with id, type and a few attributes and serialises fine when it is a single object.

uddyami commented 6 years ago

I think it should be converter.writeDocumentCollection(document)

peavers commented 6 years ago

Here is a helper method I use, just pass in the list.

    @Override
    public String writeList(Iterable<?> iterable) {
        JSONAPIDocument<Collection<?>> listJSONAPIDocument = new JSONAPIDocument<>(
                (Collection<?>) iterable);

        byte[] bytes = new byte[0];
        try {
            bytes = converter.writeDocumentCollection(listJSONAPIDocument);
        } catch (DocumentSerializationException e) {
            e.printStackTrace();
        }

        return new String(bytes);
    }
jasminb commented 6 years ago

Closing as advice for proper lib usage was provided in comments.