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

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

There is a newer version: 1.10.0
Show newest version
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;

public final class MixinWriter implements JsonWriter.WriteObject {

	private final Type manifest;
	private final FormatDescription[] descriptions;

	public MixinWriter(
			final Class manifest,
			final DslJson json,
			final FormatDescription[] descriptions) {
		this((Type) manifest, json, descriptions);
	}

	MixinWriter(
			final Type manifest,
			final DslJson json,
			final FormatDescription[] descriptions) {
		if (manifest == null) throw new IllegalArgumentException("manifest can't be null");
		if (descriptions == null || descriptions.length == 0) {
			throw new IllegalArgumentException("descriptions can't be null or empty");
		}
		this.manifest = manifest;
		this.descriptions = descriptions;
	}

	@Override
	public void write(final JsonWriter writer, final T instance) {
		if (instance == null) {
			writer.writeNull();
			return;
		}
		final Class current = instance.getClass();
		for (FormatDescription od : descriptions) {
			if (current != od.manifest) continue;
			if (od.isObjectFormatFirst) {
				od.objectFormat.write(writer, instance);
			} else {
				od.arrayFormat.write(writer, instance);
			}
			return;
		}
		throw new SerializationException("Unable to find encoder for '" + instance.getClass() + "' while encoding " + manifest.getTypeName() + ". Add @CompiledJson to specified type to allow serialization from it");
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy