All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.yahoo.elide.jsonapi.serialization.DataSerializer Maven / Gradle / Ivy

The newest version!
/*
 * Copyright 2015, Yahoo Inc.
 * Licensed under the Apache License, Version 2.0
 * See LICENSE file in project root for terms.
 */
package com.yahoo.elide.jsonapi.serialization;

import com.yahoo.elide.jsonapi.models.Data;
import com.yahoo.elide.jsonapi.models.Resource;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.IterableUtils;

import java.io.IOException;
import java.util.Collection;
import java.util.Collections;

/**
 * Custom serializer for top-level data.
 */
public class DataSerializer extends JsonSerializer> {

    @Override
    public void serialize(Data data, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
        throws IOException {
        Collection list = data.get();
        if (data.isToOne()) {
            if (CollectionUtils.isEmpty(list)) {
                jsonGenerator.writeObject(null);
                return;
            }
            jsonGenerator.writeObject(IterableUtils.first(list));
            return;
        }
        jsonGenerator.writeObject((list == null) ? Collections.emptyList() : list);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy