com.dslplatform.json.runtime.OptionalEncoder Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of dsl-json-java8 Show documentation
Show all versions of dsl-json-java8 Show documentation
DSL Platform compatible Java JSON library (https://dsl-platform.com)
package com.dslplatform.json.runtime;
import com.dslplatform.json.DslJson;
import com.dslplatform.json.JsonReader;
import com.dslplatform.json.JsonWriter;
import com.dslplatform.json.SerializationException;
import java.io.IOException;
import java.util.Optional;
public final class OptionalEncoder implements JsonWriter.WriteObject> {
private final DslJson json;
private final JsonWriter.WriteObject optWriter;
public OptionalEncoder(
final DslJson json,
final JsonWriter.WriteObject writer) {
if (json == null) throw new IllegalArgumentException("json can't be null");
this.json = json;
this.optWriter = writer;
}
@Override
public void write(JsonWriter writer, Optional value) {
if (value == null || !value.isPresent()) writer.writeNull();
else if (optWriter != null) optWriter.write(writer, value.get());
else {
final T unpacked = value.get();
if (unpacked == null) writer.writeNull();
else {
final JsonWriter.WriteObject jw = json.tryFindWriter(unpacked.getClass());
if (jw == null) throw new SerializationException("Unable to find writer for " + unpacked.getClass());
jw.write(writer, unpacked);
}
}
}
}