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

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

There is a newer version: 1.10.0
Show newest version
package com.dslplatform.json.runtime;

import com.dslplatform.json.*;

import java.util.Optional;

public final class OptionalEncoder implements JsonWriter.WriteObject> {

	private final DslJson json;
	private final JsonWriter.WriteObject encoder;

	public OptionalEncoder(
			final DslJson json,
			@Nullable final JsonWriter.WriteObject encoder) {
		if (json == null) throw new IllegalArgumentException("json can't be null");
		this.json = json;
		this.encoder = encoder;
	}

	@Override
	public void write(JsonWriter writer, @Nullable Optional value) {
		if (value == null || !value.isPresent()) writer.writeNull();
		else if (encoder != null) encoder.write(writer, value.get());
		else {
			final T unpacked = value.get();
			final JsonWriter.WriteObject jw = json.tryFindWriter(unpacked.getClass());
			if (jw == null) {
				throw new ConfigurationException("Unable to find writer for " + unpacked.getClass());
			}
			jw.write(writer, unpacked);
		}
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy