com.dslplatform.json.runtime.ArrayEncoder 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;
public final class ArrayEncoder implements JsonWriter.WriteObject {
private final DslJson json;
private final JsonWriter.WriteObject encoder;
public ArrayEncoder(
final DslJson json,
final JsonWriter.WriteObject encoder) {
if (json == null) throw new IllegalArgumentException("json can't be null");
this.json = json;
this.encoder = encoder;
}
private static final byte[] EMPTY = {'[', ']'};
@Override
public void write(final JsonWriter writer, final T[] value) {
if (value == null) writer.writeNull();
else if (value.length == 0) writer.writeAscii(EMPTY);
else if (encoder != null) {
writer.writeByte(JsonWriter.ARRAY_START);
encoder.write(writer, value[0]);
for (int i = 1; i < value.length; i++) {
writer.writeByte(JsonWriter.COMMA);
encoder.write(writer, value[i]);
}
writer.writeByte(JsonWriter.ARRAY_END);
} else {
boolean pastFirst = false;
writer.writeByte(JsonWriter.ARRAY_START);
Class> lastClass = null;
JsonWriter.WriteObject lastEncoder = null;
for (final T e : value) {
if (pastFirst) {
writer.writeByte(JsonWriter.COMMA);
} else {
pastFirst = true;
}
if (e == null) writer.writeNull();
else {
final Class> currentClass = e.getClass();
if (currentClass != lastClass) {
lastClass = currentClass;
lastEncoder = json.tryFindWriter(lastClass);
if (lastEncoder == null) {
throw new SerializationException("Unable to find writer for " + lastClass);
}
}
lastEncoder.write(writer, e);
}
}
writer.writeByte(JsonWriter.ARRAY_END);
}
}
}