对象序列化和反序列化
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了对象序列化和反序列化相关的知识,希望对你有一定的参考价值。
package com.cn.core.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class ObjectConvertor { /** * 序列化 * @param obj * @return */ public static byte[] serialize(Object obj) { if (obj == null) { throw new NullPointerException("Can‘t serialize null"); } byte[] object = null; ByteArrayOutputStream bos = null; ObjectOutputStream os = null; try { bos = new ByteArrayOutputStream(); os = new ObjectOutputStream(bos); os.writeObject(obj); object = bos.toByteArray(); } catch (IOException e) { throw new IllegalArgumentException("Non-serializable object", e); } finally { try { if (os != null) os.close(); if (bos != null) bos.close(); } catch (Exception ex) { ex.printStackTrace(); } } return object; } /** * 反序列化 * @param in * @return */ public static Object deserialize(byte[] bt) { Object object = null; ByteArrayInputStream bis = null; ObjectInputStream is = null; try { if (bt != null) { bis = new ByteArrayInputStream(bt); is = new ObjectInputStream(bis); object = is.readObject(); is.close(); bis.close(); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) is.close(); if (bis != null) bis.close(); } catch (Exception e2) { e2.printStackTrace(); } } return object; } }
以上是关于对象序列化和反序列化的主要内容,如果未能解决你的问题,请参考以下文章
将 Objective-C 对象序列化和反序列化为 JSON
com.fasterxml.jackson包序列化json对象和反序列化