Redis中对象的序列化和序列化的使用

最近项目开发用到Redis,然后使用到了将对象进行序列化和反序列化的方法,总结如下:
package com.lz.test;

import java.nio.charset.Charset;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.data.redis.serializer.SerializationException;

public class JsonRedisSeriaziler {
	public static final String EMPTY_JSON = "{}";

	public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

	protected static ObjectMapper objectMapper = new ObjectMapper();

	public JsonRedisSeriaziler() {
	}

	/**
	 * java-object as json-string
	 * 
	 * @param object
	 * @return
	 */
	public static String seriazileAsString(Object object) {
		if (object == null) {
			return EMPTY_JSON;
		}
		try {
			return this.objectMapper.writeValueAsString(object);
		} catch (Exception ex) {
			throw new SerializationException("Could not write JSON: "
					+ ex.getMessage(), ex);
		}
	}

	/**
	 * json-string to java-object
	 * 
	 * @param str
	 * @return
	 */
	public static <T> T deserializeAsObject(String str, Class<T> clazz) {
		if (str == null || clazz == null) {
			return null;
		}
		try {
			return this.objectMapper.readValue(str, clazz);
		} catch (Exception ex) {
			throw new SerializationException("Could not write JSON: "
					+ ex.getMessage(), ex);
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_21190979/article/details/72997012