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

net.hamnaberg.json.codec.JsonCodec Maven / Gradle / Ivy

The newest version!
package net.hamnaberg.json.codec;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.function.Function;

public interface JsonCodec extends EncodeJson, DecodeJson {
    default  JsonCodec xmap(Function f, Function g) {
        return JsonCodec.lift(value -> fromJson(value).map(f), value -> toJson(g.apply(value)));
    }

    default  JsonCodec xmapi(Iso iso) {
        return xmap(iso::get, iso::reverseGet);
    }

    default  JsonCodec narrow(Function> f, Function g) {
        return JsonCodec.lift(tryMap(f), value -> toJson(g.apply(value)));
    }

    default  JsonCodec tryNarrow(Function f, Function g) {
        return narrow(a -> () -> f.apply(a), g);
    }

    @Override
    default JsonCodec> option() {
        return Codecs.optionalCodec(this);
    }

    @Override
    default JsonCodec> list() {
        return Codecs.listCodec(this);
    }

    default NamedJsonCodec field(String name) {
        return NamedJsonCodec.of(name, this);
    }

    @Override
    default JsonCodec withDefaultValue(A defaultValue) {
        return lift(new DecodeJsonWithDefault<>(this, defaultValue), this);
    }

    static  JsonCodec lift(DecodeJson decoder, EncodeJson encoder) {
        return lift(decoder, encoder, Optional.empty());
    }

    static  JsonCodec lift(DecodeJson decoder, EncodeJson encoder, Optional defaultValue) {
        return new DefaultJsonCodec<>(defaultValue.map(decoder::withDefaultValue).orElse(decoder), encoder);
    }
}