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

最近项目开发用到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 deserializeAsObject(String str, Class 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);
		}
	}
}

 

你可能感兴趣的:(对象的序列化和序列化的使用)