package com.sdyc.ndmp.protobuf.serializer; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; import java.io.IOException; /** *
 *
 * Created by IntelliJ IDEA.
 * User: zhenqin
 * Date: 14/11/14
 * Time: 13:08
 * To change this template use File | Settings | File Templates.
 *
 * 
* * @author zhenqin */ public class JacksonSerializer implements Serializer { private static final long serialVersionUID = 1L; /** * String byte */ private StringSerializer serializer = new StringSerializer(); /** * 类对象, 用于Object json to Object 的转换 */ private Class reverseClazz; private ObjectMapper objectMapper; public JacksonSerializer(String reverseClazz) { try { this.reverseClazz = (Class) Class.forName(reverseClazz); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(e); } objectMapper = new ObjectMapper(); objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); objectMapper.configure(SerializationConfig.Feature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS, true); } public JacksonSerializer(Class clazz) { this.reverseClazz = clazz; objectMapper = new ObjectMapper(); objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); objectMapper.configure(SerializationConfig.Feature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS, true); } @Override public byte[] serialize(T t) { try { String s = objectMapper.writeValueAsString(t); return serializer.serialize(s); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public T deserialize(byte[] bytes) { try { return objectMapper.readValue(serializer.deserialize(bytes), reverseClazz); } catch (IOException e) { throw new IllegalArgumentException(e); } } public Class getReverseClazz() { return reverseClazz; } public ObjectMapper getObjectMapper() { return objectMapper; } }