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

io.polaris.core.json.Jsons Maven / Gradle / Ivy

There is a newer version: 3.2.1
Show newest version
package io.polaris.core.json;

import java.lang.reflect.Type;
import java.util.List;

import javax.annotation.Nullable;

import io.polaris.core.lang.TypeRef;
import io.polaris.core.log.ILogger;
import io.polaris.core.log.ILoggers;
import io.polaris.core.service.Service;
import io.polaris.core.service.ServiceLoader;
import io.polaris.core.service.StatefulServiceLoader;
import io.polaris.core.tuple.ValueRef;

/**
 * @author Qt
 * @since 1.8,  Feb 04, 2024
 */
public class Jsons {
	private static final ILogger log = ILoggers.of(Jsons.class);
	private static volatile ValueRef ref;

	@Nullable
	public static JsonSerializer getJsonSerializer() {
		if (ref != null) {
			return ref.get();
		}
		synchronized (Jsons.class) {
			if (ref != null) {
				return ref.get();
			}
			ref = new ValueRef<>(loadJsonSerializer());
			return ref.get();
		}
	}

	@Nullable
	private static JsonSerializer loadJsonSerializer() {
		try {
			ServiceLoader serviceLoader = StatefulServiceLoader.load(JsonSerializer.class).serviceLoader();
			List> providers = serviceLoader.getProviders();
			for (Service provider : providers) {
				try {
					JsonSerializer jsonSerializer = provider.getSingleton();
					return jsonSerializer;
				} catch (Throwable e) {
					log.error(e, "Failed to load json serializer");
				}
			}
		} catch (Throwable e) {
			log.error(e, "Failed to load json serializer");
		}
		return null;
	}

	public static String serialize(Object value) {
		JsonSerializer jsonSerializer = getJsonSerializer();
		if (jsonSerializer != null) {
			return jsonSerializer.serialize(value);
		}
		throw new UnsupportedOperationException();
	}

	public static  T deserialize(String json, Type type) {
		JsonSerializer jsonSerializer = getJsonSerializer();
		if (jsonSerializer != null) {
			return jsonSerializer.deserialize(json, type);
		}
		throw new UnsupportedOperationException();
	}

	public static  T deserialize(String json, Class type) {
		JsonSerializer jsonSerializer = getJsonSerializer();
		if (jsonSerializer != null) {
			return jsonSerializer.deserialize(json, type);
		}
		throw new UnsupportedOperationException();
	}

	public static  T deserialize(String json, TypeRef type) {
		JsonSerializer jsonSerializer = getJsonSerializer();
		if (jsonSerializer != null) {
			return jsonSerializer.deserialize(json, type);
		}
		throw new UnsupportedOperationException();
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy