非通用序列化与反序列化

Java非通用序列化与反序列化

使用场景
在出价列表缓存跟新里需要在存放数据之前进行序列化,在取出数据之后需要反序列化成Java对象才能使用。在用户创建一笔订单时将Tair里的数据取出来反序列化成BizOrderList 然后采用插入排序算法更新BizOrderList,最后将BizOrderList序列化存入Tair,这样就完成了Tair缓存的更新。
原理分析
示例类:Seri。
class Seri
{
Int a;
String str;
}
序列化过程:
将int a 放入固定大小的ByteBuffer(字节数组)首部部分空间,占用ByteBuffer长度为4字节。将String str 转换成字节数组(str.getBytes()),得到str.getBytes()的长度(str.getBytes().length)。另外用4个字节(就是int长度)的ByteBuffer空间存放str字节数组的大小。再用上str.getBytes().length长度的空间存放str.getBytes()。
所以总的ByteBuffer大小为sizeof(int)+ sizeof(int)+str.getBytes().length。


占用空间大小
sizeof(int) 占用空间大小
sizeof(int)
占用空间大小
str.getBytes().length






反序列化过程:
将首部大小为sizeof(int)的数据取出ByteBuffer.getInt()。还原成int a= ByteBuffer.getInt();将第二个sizeof(int)大小的数据取出int length= ByteBuffer.getInt();length是str字节数组大小。
byte[] bytes = new byte[length];buffer.get(bytes);然后还原String str = new String(bytes, "GBK");最后还原成class Seri。
使用示例

import java.nio.ByteBuffer;

public class testbytes
{

ByteBuffer byteBuffer=null;

Seri seri = new Seri(4,"dsafasfadsf");

/**
* 序列化
*/
public void Seri()
{
int length = seri.str.getBytes().length;
System.out.println("length:" + length);
byteBuffer = ByteBuffer.allocate( 4 + 4 + length );

byteBuffer.putInt(seri.a);

byteBuffer.putInt(length);

byteBuffer.put(seri.str.getBytes());

System.out.println("byteBuffer:" + byteBuffer);
}

/**
* 反序列化
*/
public Seri popupSeri()
{
Seri seri=null;
byteBuffer.position(0);
int a = byteBuffer.getInt();
System.out.println("a:" + a);
int length = byteBuffer.getInt();
System.out.println("length:" + length);

try
{
byte[] bytes = new byte[length];
byteBuffer.get(bytes);
seri = new Seri(a,new String(bytes, "GBK"));
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("seri:" + seri + "seri.a:" + seri.a + "seri.str:" + seri.str );
return seri;
}

/**
* @param args
*/
public static void main(String[] args)
{
testbytes Testbytes = new testbytes();

Testbytes.Seri();

Seri seri = Testbytes.popupSeri();
}

}

class Seri
{
public int a;
public String str;

public Seri(int a,String str)
{
this.a=a;
this.str=str;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值