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

io.github.whimthen.kits.json.support.GsonSupport Maven / Gradle / Ivy

There is a newer version: 1.0.4-RELEASE
Show newest version
package io.github.whimthen.kits.json.support;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import io.github.whimthen.kits.interfaces.JsonSupport;
import io.github.whimthen.kits.log.Logger;

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

/**
 * Json数据操作工具类
 *
 * @project: kits
 * @created: with IDEA
 * @author: kits
 * @Date: 2018 09 26 7:53 PM | September. Wednesday
 */
public class GsonSupport implements JsonSupport {

	private final Gson gson = new GsonBuilder()
						.disableHtmlEscaping()
						.serializeNulls()
						.create();

	/**
	 * 将对象转换为json
	 *
	 * @param object	需要转换的对象
	 * @return			转换后的字符串
	 */
	@Override
	public String toJson(Object object) {
		try {
			String result;
			if (object instanceof String || object instanceof Character) {
				result = object.toString();
			} else {
				result = gson.toJson(object);
			}
			return result;
		} catch (Exception ex) {
			Logger.error(ex);
			return null;
		}
	}

	/**
	 * 将json转换为对象
	 *
	 * @param jsonStr	json字符串
	 * @param clazz		转换后的类型
	 * @return			转换后的对象
	 */
	@Override
	public T toObject(String jsonStr, Class clazz) {
		try {
			return gson.fromJson(jsonStr, clazz);
		} catch (Exception ex) {
			Logger.error(ex);
			return null;
		}
	}

	/**
	 * 将json转换为指定类型的对象集合
	 *
	 * @param jsonStr		json字符串
	 * @param clazz	目标类型
	 * @return				转换后的对象
	 */
	@Override
	public List toList(String jsonStr, Class clazz) {
		try {
			return gson.fromJson(jsonStr, new ParameterizedTypeImpl(List.class, new Class[]{clazz}));
		} catch (Exception ex) {
			Logger.error(ex);
			return null;
		}
	}

	@Override
	public String prettyJson(Object object) {
		Gson g = gson.newBuilder().setPrettyPrinting().create();
		if (object instanceof String || object instanceof Character) {
			try {
				object = toObject(object.toString(), (Class) Map.class);
			} catch (Throwable throwable) {

			}
		}
		return g.toJson(object);
	}

	/**
	 * 构造Type
	 */
	protected static class ParameterizedTypeImpl implements ParameterizedType {

		private final Class raw;

		private final Type[] args;

		ParameterizedTypeImpl(Class raw, Type[] args) {
			this.raw = raw;
			this.args = args != null ? args : new Type[0];
		}

		@Override
		public Type[] getActualTypeArguments() {
			return args;
		}

		@Override
		public Type getRawType() {
			return raw;
		}

		@Override
		public Type getOwnerType() {return null;}

	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy