Gson google json使用

首先json将处理的类型分为:


Gson google json使用_第1张图片


要把java对象和json之前转换使用 com.google.gson.Gson对象的toJson()和fromJson()

gson可对不同对象的序列化转换进行自定义:

通过GsonBuilder中注册类型适配器

JSONUtils.java

import java.lang.reflect.Type;

import com.google.gson.GsonBuilder;
import com.the4thcity.commons.time.DateFormat;

public class JSONUtils {

	public static final GsonBuilder defaultGsonBuilder = defaultGsonBuilder();

	/**
	 * get default GsonBuilder
	 * 
	 * @return
	 */
	public static GsonBuilder defaultGsonBuilder() {
		GsonBuilder builder = new GsonBuilder();

		builder.registerTypeAdapter(java.sql.Timestamp.class, new TimestampAdapter());
		//	builder.setLongSerializationPolicy(LongSerializationPolicy.STRING);
		builder.serializeSpecialFloatingPointValues();//處理特殊的NaN
		builder.setDateFormat(DateFormat.YYYY_MM_DD_HH24_MM_SS);

		return builder;

	}

	/**
	 * convert object to json
	 * 
	 * @param src
	 * @return
	 */
	public static String toJson(Object src) {
		return defaultGsonBuilder.create().toJson(src);
	}

	/**
	 * convert json string to java object
	 * 
	 * @param <T>
	 * @param json
	 * @param type
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T fromJson(String json, Type type) {
		return (T) defaultGsonBuilder.create().fromJson(json, type);//強制轉換為T,不然ant編譯報錯
	}
TimestampAdapter.java
import java.lang.reflect.Type;
import java.sql.Timestamp;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.the4thcity.commons.time.DateFormat;

public class TimestampAdapter implements JsonDeserializer<Timestamp>, JsonSerializer<Timestamp> {

	@Override
	public Timestamp deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
			throws JsonParseException {
		return Timestamp.valueOf(json.getAsString().replace("T", " "));
	}

	@Override
	public JsonElement serialize(Timestamp src, Type typeOfSrc, JsonSerializationContext context) {
		String dateFormatAsString = DateFormat.formatYMDH24MS(src);
		return new JsonPrimitive(dateFormatAsString);
	}

}


你可能感兴趣的:(Gson google json使用)