简体   繁体   English

将Integer集合序列化为字节数组,然后反序列化

[英]Serialize Integer collection to byte array and deserialize it back

I need to have serialization and deserialization of Collection<Integer> for storing it in Redis which requires byte[] . 我需要对Collection<Integer>进行序列化和反序列化,以将其存储在需要byte[] Redis中。 I've found a code using ByteBuffer and IntBuffer for serialization: 我发现了使用ByteBufferIntBuffer进行序列化的代码:

byte[] serializeIntegerCollection(Collection<Integer> collection) {
    ByteBuffer byteBuffer = ByteBuffer.allocate(collection.size() * 4);
    IntBuffer intBuffer = byteBuffer.asIntBuffer();
    collection.forEach(intBuffer::put);
    return byteBuffer.array();
}

And now the code I try to use for deserialization: 现在我尝试用于反序列化的代码:

Collection<Integer> deserializeIntegerCollection(byte[] bytes) {
    ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
    IntBuffer intBuffer = byteBuffer.asIntBuffer();
    return asList(intBuffer.array());
}

But intBuffer.array() throws UnsupportedOperationException . 但是intBuffer.array()抛出UnsupportedOperationException What's wrong with it and how to handle the issue? 它有什么问题以及如何处理该问题?

you can serialize it like. 您可以像序列化它。 serializeIntegerCollection class must implements serializable . serializeIntegerCollection类必须实现serializable


ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(list);
byte[] bytes = bos.toByteArray();

you can deserialize it like. 您可以像这样反序列化。 deserializeIntegerCollectionclass deserializeIntegerCollectionclass

ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes)); @SuppressWarnings("unchecked") Collection<Integer> collection= (Collection<Integer>) ois.readObject();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将Httpclient的响应object序列化和反序列化为字节数组 - How to serialize & deserialize response object of Httpclient into byte array 通过网络和字节数组序列化/反序列化Java对象 - Serialize/Deserialize Java object through network and byte array 如何使用 Jackson 和包装器 object 反序列化/序列化字节数组 - how to deserialize / serialize byte array using Jackson and wrapper object 如何将内部没有 Serializable 字段的 java 对象序列化为字节数组并反序列化该数组以获取原始对象 - How to serialize a java object with not Serializable fields inside it into byte array and deserialize the array to get the original object 对于我的项目,我想将一个整数转换为字节数组,将字节数组转换回整数 - For my project I want to convert an integer into byte array and byte array back to integer 当我有一个黑盒子转换为/从字节数组转换时,如何在Java中序列化和反序列化? - How do I serialize and deserialize in Java when I have a black box to convert to/from a byte array? Jackson - 使用整数字段序列化/反序列化枚举 - Jackson - Serialize / Deserialize Enums with Integer fields 从rgb-integer转换为字节数组然后返回不起作用 - Conversion from rgb-integer to byte array and back does not work 反序列化集合到外部数组 - Deserialize collection into outer array 将整数转换为字节数组,并将字节数组转换为整数 - Convert integer to byte array and byte array to Integer
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM