加入依赖:json序列化

    1. <dependency>
    2. <groupId>com.google.code.gson</groupId>
    3. <artifactId>gson</artifactId>
    4. <version>2.8.5</version>
    5. </dependency>
    1. package com.lms.jdk8.serialize;
    2. import com.google.gson.Gson;
    3. import java.io.*;
    4. import java.nio.charset.StandardCharsets;
    5. /**
    6. * @Author: 李孟帅
    7. * @Date: 2021-12-09 21:14
    8. * @Description:
    9. */
    10. public enum Serializer {
    11. JDK {
    12. @Override
    13. <T> byte[] serialize(T object) {
    14. try {
    15. ByteArrayOutputStream bos = new ByteArrayOutputStream();
    16. ObjectOutputStream oos = new ObjectOutputStream(bos);
    17. oos.writeObject(object);
    18. return bos.toByteArray();
    19. } catch (IOException e) {
    20. throw new RuntimeException("序列化失败", e);
    21. }
    22. }
    23. @Override
    24. <T> T deserialize(byte[] bytes, Class<T> clazz) {
    25. try {
    26. ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
    27. return (T) ois.readObject();
    28. } catch (IOException | ClassNotFoundException e) {
    29. throw new RuntimeException("反序列化失败", e);
    30. }
    31. }
    32. },
    33. JSON {
    34. @Override
    35. <T> byte[] serialize(T object) {
    36. Gson gson = new Gson();
    37. String json = gson.toJson(object);
    38. return json.getBytes(StandardCharsets.UTF_8);
    39. }
    40. @Override
    41. <T> T deserialize(byte[] bytes, Class<T> clazz) {
    42. Gson gson = new Gson();
    43. return gson.fromJson(new String(bytes, StandardCharsets.UTF_8), clazz);
    44. }
    45. };
    46. // 序列化
    47. abstract <T> byte[] serialize(T object);
    48. // 反序列化
    49. abstract <T> T deserialize(byte[] bytes, Class<T> clazz);
    50. }