JacksonSerializer.java 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package com.sdyc.ndmp.protobuf.serializer;
  2. import org.codehaus.jackson.map.ObjectMapper;
  3. import org.codehaus.jackson.map.SerializationConfig;
  4. import java.io.IOException;
  5. /**
  6. * <pre>
  7. *
  8. * Created by IntelliJ IDEA.
  9. * User: zhenqin
  10. * Date: 14/11/14
  11. * Time: 13:08
  12. * To change this template use File | Settings | File Templates.
  13. *
  14. * </pre>
  15. *
  16. * @author zhenqin
  17. */
  18. public class JacksonSerializer<T> implements Serializer<T> {
  19. private static final long serialVersionUID = 1L;
  20. /**
  21. * String byte
  22. */
  23. private StringSerializer serializer = new StringSerializer();
  24. /**
  25. * 类对象, 用于Object json to Object 的转换
  26. */
  27. private Class<? extends T> reverseClazz;
  28. private ObjectMapper objectMapper;
  29. public JacksonSerializer(String reverseClazz) {
  30. try {
  31. this.reverseClazz = (Class<T>) Class.forName(reverseClazz);
  32. } catch (ClassNotFoundException e) {
  33. throw new IllegalArgumentException(e);
  34. }
  35. objectMapper = new ObjectMapper();
  36. objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
  37. objectMapper.configure(SerializationConfig.Feature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS, true);
  38. }
  39. public JacksonSerializer(Class<? extends T> clazz) {
  40. this.reverseClazz = clazz;
  41. objectMapper = new ObjectMapper();
  42. objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
  43. objectMapper.configure(SerializationConfig.Feature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS, true);
  44. }
  45. @Override
  46. public byte[] serialize(T t) {
  47. try {
  48. String s = objectMapper.writeValueAsString(t);
  49. return serializer.serialize(s);
  50. } catch (IOException e) {
  51. throw new IllegalStateException(e);
  52. }
  53. }
  54. @Override
  55. public T deserialize(byte[] bytes) {
  56. try {
  57. return objectMapper.readValue(serializer.deserialize(bytes), reverseClazz);
  58. } catch (IOException e) {
  59. throw new IllegalArgumentException(e);
  60. }
  61. }
  62. public Class<? extends T> getReverseClazz() {
  63. return reverseClazz;
  64. }
  65. public ObjectMapper getObjectMapper() {
  66. return objectMapper;
  67. }
  68. }