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

com.dslplatform.json.runtime.ArrayDecoder Maven / Gradle / Ivy

The newest version!
package com.dslplatform.json.runtime;

import com.dslplatform.json.JsonReader;
import com.dslplatform.json.Nullable;

import java.io.IOException;
import java.util.ArrayList;

public final class ArrayDecoder implements JsonReader.ReadObject {

	private final T[] emptyInstance;
	private final JsonReader.ReadObject decoder;

	public ArrayDecoder(
			final T[] emptyInstance,
			final JsonReader.ReadObject decoder) {
		if (emptyInstance == null) throw new IllegalArgumentException("emptyInstance can't be null");
		if (decoder == null) throw new IllegalArgumentException("decoder can't be null");
		this.emptyInstance = emptyInstance;
		this.decoder = decoder;
	}

	@Nullable
	@Override
	public T[] read(final JsonReader reader) throws IOException {
		if (reader.wasNull()) return null;
		if (reader.last() != '[') throw reader.newParseError("Expecting '[' for array start");
		if (reader.getNextToken() == ']') return emptyInstance;
		final ArrayList list = new ArrayList<>(4);
		list.add(decoder.read(reader));
		while (reader.getNextToken() == ','){
			reader.getNextToken();
			list.add(decoder.read(reader));
		}
		if (reader.last() != ']') throw reader.newParseError("Expecting ']' for array end");
		return list.toArray(emptyInstance);
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy