com.dslplatform.json.runtime.LazyAttributeObjectEncoder 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.JsonWriter;
import com.dslplatform.json.SerializationException;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.function.Function;
class LazyAttributeObjectEncoder implements JsonWriter.WriteObject {
private static final Charset utf8 = Charset.forName("UTF-8");
private final Function read;
private final byte[] quotedName;
private final boolean alwaysSerialize;
private JsonWriter.WriteObject encoder;
private final DslJson json;
private final Type type;
LazyAttributeObjectEncoder(
final Function read,
final String name,
final DslJson json,
final Type type) {
if (read == null) throw new IllegalArgumentException("read can't be null");
if (name == null || name.isEmpty()) throw new IllegalArgumentException("name can't be null");
if (json == null) throw new IllegalArgumentException("json can't be null");
this.read = read;
quotedName = ("\"" + name + "\":").getBytes(utf8);
this.alwaysSerialize = !json.omitDefaults;
this.json = json;
this.type = type;
}
@Override
public void write(final JsonWriter writer, final T value) {
if (type != null && encoder == null) {
encoder = json.tryFindWriter(type);
if (encoder == null) {
throw new SerializationException("Unable to find writer for " + type);
}
}
final R attr = read.apply(value);
if (type == null) {
if (attr == null) {
if (alwaysSerialize) {
writer.writeAscii(quotedName);
writer.writeNull();
}
} else {
final JsonWriter.WriteObject tmp = json.tryFindWriter(attr.getClass());
if (tmp == null) {
throw new SerializationException("Unable to find writer for " + attr.getClass());
}
writer.writeAscii(quotedName);
tmp.write(writer, attr);
}
} else if (alwaysSerialize || attr != null) {
writer.writeAscii(quotedName);
encoder.write(writer, attr);
}
}
}