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

io.vavr.gson.TraversableConverter Maven / Gradle / Ivy

There is a newer version: 0.10.2
Show newest version
/*                        __    __  __  __    __  ___
 *                       \  \  /  /    \  \  /  /  __/
 *                        \  \/  /  /\  \  \/  /  /
 *                         \____/__/  \__\____/__/.ɪᴏ
 * ᶜᵒᵖʸʳᶦᵍʰᵗ ᵇʸ ᵛᵃᵛʳ ⁻ ˡᶦᶜᵉⁿˢᵉᵈ ᵘⁿᵈᵉʳ ᵗʰᵉ ᵃᵖᵃᶜʰᵉ ˡᶦᶜᵉⁿˢᵉ ᵛᵉʳˢᶦᵒⁿ ᵗʷᵒ ᵈᵒᵗ ᶻᵉʳᵒ
 */
package io.vavr.gson;

import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonParseException;
import io.vavr.collection.Stream;
import io.vavr.collection.Traversable;

import java.lang.reflect.Type;
import java.util.function.Function;

class TraversableConverter> extends JsonArrayConverter {

    private final Function, Traversable> factory;

    TraversableConverter(Function, Traversable> factory) {
        this.factory = factory;
    }

    @Override
    @SuppressWarnings("unchecked")
    T fromJsonArray(JsonArray arr, Type type, Type[] subTypes, JsonDeserializationContext ctx) throws JsonParseException {
        Stream stream = Stream.ofAll(arr).map(e -> subTypes.length == 1 ? ctx.deserialize(e, subTypes[0]) : e);
        return (T) factory.apply(stream);
    }

    @Override
    Traversable toTraversable(T src) {
        return src;
    }
}