• Java序列化对象-字符串转换


     1 package com.test;
     2 
     3 import com.alibaba.fastjson.JSON;
     4 import org.junit.Test;
     5 
     6 import java.io.ByteArrayInputStream;
     7 import java.io.ByteArrayOutputStream;
     8 import java.io.ObjectInputStream;
     9 import java.io.ObjectOutputStream;
    10 
    11 public class SerializeTest {
    12     @Test
    13     public void Test()throws Exception{
    14         AgencyVoInfo dept = new AgencyVoInfo();
    15         dept.setAgencyCode("1");
    16         dept.setAgencyName("2");
    17         dept.setBranchCode("3");
    18         dept.setId(1);
    19         dept.setSerialNo(1);
    20         String objectStr = serializeObject(dept);
    21         System.out.println(objectStr);
    22         AgencyVoInfo dept2 = (AgencyVoInfo)stringSerializeObject(objectStr);
    23         System.out.println(JSON.toJSON(dept2));
    24     }
    25     /**
    26      * 对象序列化为字符串
    27      * @param object
    28      * @return
    29      */
    30     public static String serializeObject(Object object)throws Exception{
    31         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    32         ObjectOutputStream out = new ObjectOutputStream(byteArrayOutputStream);
    33         out.writeObject(object);
    34                                                                   //必须是ISO-8859-1
    35         String objectStr = byteArrayOutputStream.toString("ISO-8859-1");
    36         out.close();
    37         byteArrayOutputStream.close();
    38         return objectStr;
    39     }
    40 
    41     /**
    42      * 字符串序列化为对象
    43      * @param objectStr
    44      * @return
    45      * @throws Exception
    46      */
    47     public static Object stringSerializeObject(String objectStr)throws Exception{
    49         ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(objectStr.getBytes("ISO-8859-1"));
    50         ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
    51         Object object =  objectInputStream.readObject();
    52         objectInputStream.close();
    53         byteArrayInputStream.close();
    54         return object;
    55     }
    56 }
  • 相关阅读:
    Nova官方资料入口处
    LeetCode 有效的数独
    LeetCode 两数之和
    LeetCode 移动零
    安装OpenStack Queens版本的教程推荐
    删除排序数组中的重复项
    (转载)OpenStack client 调用分析
    (转载)基于Linux C的socket抓包程序和Package分析
    Maven的具体使用和优点
    关于 Javascript 学习,有哪些好的博客或者网站推荐?
  • 原文地址:https://www.cnblogs.com/qinxu/p/8465090.html
Copyright © 2020-2023  润新知