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

com.github.bloodshura.ignitium.cfg.json.JsonArray Maven / Gradle / Ivy

package com.github.bloodshura.ignitium.cfg.json;

import com.github.bloodshura.ignitium.cfg.json.handling.JsonComposer;
import com.github.bloodshura.ignitium.cfg.json.handling.JsonParser;
import com.github.bloodshura.ignitium.collection.list.impl.XLinkedList;
import com.github.bloodshura.ignitium.resource.InMemoryOutputResource;
import com.github.bloodshura.ignitium.resource.OutputResource;
import com.github.bloodshura.ignitium.resource.Resource;
import com.github.bloodshura.ignitium.resource.StringResource;

import javax.annotation.Nonnull;
import java.io.IOException;

public final class JsonArray extends XLinkedList implements Json {
	public JsonArray() {
	}

	public JsonArray(@Nonnull CharSequence content) throws IOException, JsonParseException {
		this(new StringResource(content));
	}

	public JsonArray(@Nonnull Iterable values) {
		super(values);
	}

	public JsonArray(@Nonnull Resource resource) throws IOException, JsonParseException {
		load(resource);
	}

	@Override
	public void load(@Nonnull Resource resource) throws IOException, JsonParseException {
		clear();

		Object result = JsonParser.parse(resource);

		if (result instanceof JsonArray) {
			addAll((JsonArray) result);
		} else if (result != null) {
			add(result);
		}
	}

	@Override
	public void save(@Nonnull OutputResource resource) throws IOException {
		JsonComposer.compose(this, resource, true);
	}

	@Nonnull
	@Override
	public String toString() {
		return toString(true);
	}

	@Nonnull
	public String toString(boolean pretty) {
		try {
			InMemoryOutputResource resource = new InMemoryOutputResource();

			JsonComposer.compose(this, resource, pretty);

			return resource.getString();
		} catch (IOException exception) { // Teorically, should not happen...
			return super.toString();
		}
	}
}