12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- package com.sdyc.ndmp.protobuf.serializer;
- import org.codehaus.jackson.map.ObjectMapper;
- import org.codehaus.jackson.map.SerializationConfig;
- import java.io.IOException;
- /**
- * <pre>
- *
- * Created by IntelliJ IDEA.
- * User: zhenqin
- * Date: 14/11/14
- * Time: 13:08
- * To change this template use File | Settings | File Templates.
- *
- * </pre>
- *
- * @author zhenqin
- */
- public class JacksonSerializer<T> implements Serializer<T> {
- private static final long serialVersionUID = 1L;
- /**
- * String byte
- */
- private StringSerializer serializer = new StringSerializer();
- /**
- * 类对象, 用于Object json to Object 的转换
- */
- private Class<? extends T> reverseClazz;
- private ObjectMapper objectMapper;
- public JacksonSerializer(String reverseClazz) {
- try {
- this.reverseClazz = (Class<T>) 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<? extends T> 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<? extends T> getReverseClazz() {
- return reverseClazz;
- }
- public ObjectMapper getObjectMapper() {
- return objectMapper;
- }
- }
|