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);
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy