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

gsonpath.internal.CollectionTypeAdapter Maven / Gradle / Ivy

Go to download

An annotation processor which generates Type Adapters for the Google Gson library

There is a newer version: 4.0.0
Show newest version
package gsonpath.internal;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * A collection type adapter that delegates and read and write functions to a provided type adapter.
 * The underlying collection type is a {@link List}.
 *
 * @param  the object type to serialize/deserialize.
 */
public final class CollectionTypeAdapter extends TypeAdapter> {
    private final TypeAdapter componentTypeAdapter;
    private boolean filterNulls;

    public CollectionTypeAdapter(TypeAdapter componentTypeAdapter, boolean filterNulls) {
        this.componentTypeAdapter = componentTypeAdapter;
        this.filterNulls = filterNulls;
    }

    @Override
    public Collection read(JsonReader in) throws IOException {
        if (in.peek() == JsonToken.NULL) {
            in.nextNull();
            return null;
        }

        List list = new ArrayList<>();
        in.beginArray();
        while (in.hasNext()) {
            E instance = componentTypeAdapter.read(in);

            if (filterNulls && instance == null) {
                continue;
            }

            list.add(instance);
        }
        in.endArray();
        return list;
    }

    @SuppressWarnings("unchecked")
    @Override
    public void write(JsonWriter out, Collection list) throws IOException {
        if (list == null) {
            out.nullValue();
            return;
        }

        out.beginArray();
        for (E element : list) {
            componentTypeAdapter.write(out, element);
        }
        out.endArray();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy