JsonReader.java

/***************************************************************************
   Copyright 2014 Emily Estes

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
***************************************************************************/
package net.metanotion.json;


/** Collate the series events into an instance of a Json value. This class is used to produce concrete instances of a
JsonObject or JsonArray from JSON encoded string.
	@param <T> the type of value expected to be produced from the JSON encoded string.
*/
public final class JsonReader<T> implements Handler<T>, Continuation<Object,T> {
	private Object val = null;

	@Override public Handler<T> resume(final Object value) {
		this.val = value;
		return this;
	}

	@Override public Handler<T> start() { return this; }
	@Override public T finish() { return (T) val; }

	@Override public Handler<T> startObject() { return new ObjectReader<T>(this); }
	@Override public Handler<T> key(final String key) {
		throw new RuntimeException("Unexpected Json token, was expecting a value, got a key.");
	}
	@Override public Handler<T> endObject() {
		throw new RuntimeException("Unexpected Json token, was expecting a value, instead terminated object.");
	}

	@Override public Handler<T> startList() { return new ListReader<T>(this); }
	@Override public Handler<T> endList() {
		throw new RuntimeException("Unexpected Json token, was expecting a value, instead terminated list.");
	}

	@Override public Handler<T> integer(final Long value) { return resume(value); }
	@Override public Handler<T> decimal(final Double value) { return resume(value); }
	@Override public Handler<T> string(final String value) { return resume(value); }
	@Override public Handler<T> bool(final boolean value) { return resume(value); }
	@Override public Handler<T> jsonNull() { return resume(null); }
}