JSONSerializer.java 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * Copyright 2010-2011 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.sdyc.ndmp.protobuf.serializer;
  17. import com.alibaba.fastjson.JSON;
  18. /**
  19. * Java Serialization Redis strserializer.
  20. * Delegates to the default (Java based) strserializer in Spring 3.
  21. *
  22. * <pre>
  23. *
  24. * Created by IntelliJ IDEA.
  25. * User: zhenqin
  26. * Date: 13-11-13
  27. * Time: 上午8:58
  28. * To change this template use File | Settings | File Templates.
  29. *
  30. * </pre>
  31. *
  32. * @author zhenqin
  33. */
  34. public class JSONSerializer<T> implements Serializer<T> {
  35. private static final long serialVersionUID = 1L;
  36. /**
  37. * String byte
  38. */
  39. private StringSerializer serializer = new StringSerializer();
  40. /**
  41. * 类对象, 用于Object json to Object 的转换
  42. */
  43. private Class<? extends T> reverseClazz;
  44. public JSONSerializer(Class<? extends T> clazz) {
  45. this.reverseClazz = clazz;
  46. }
  47. public JSONSerializer(String classString) {
  48. try {
  49. this.reverseClazz = (Class)Class.forName(classString);
  50. } catch (ClassNotFoundException e) {
  51. throw new IllegalArgumentException(e);
  52. }
  53. }
  54. @Override
  55. public byte[] serialize(T o) {
  56. return serializer.serialize(JSON.toJSONString(o));
  57. }
  58. @Override
  59. public T deserialize(byte[] bytes) {
  60. return JSON.toJavaObject(
  61. JSON.parseObject(serializer.deserialize(bytes)), reverseClazz);
  62. }
  63. public Class<? extends T> getReverseClazz() {
  64. return reverseClazz;
  65. }
  66. }