序列化框架——protostuff

因为protobuf用起来不太方便,然后产生了protostuff——Protostuff is the stuff that leverages google's protobuf.

1、maven依赖:

                <dependency>
			<groupId>io.protostuff</groupId>
			<artifactId>protostuff-core</artifactId>
			<version>1.6.0</version>
		</dependency>

		<dependency>
			<groupId>io.protostuff</groupId>
			<artifactId>protostuff-runtime</artifactId>
			<version>1.6.0</version>
		</dependency>

或者

		<dependency>
			<groupId>com.dyuproject.protostuff</groupId>
			<artifactId>protostuff-core</artifactId>
			<version>1.1.3</version>
		</dependency>

		<dependency>
			<groupId>com.dyuproject.protostuff</groupId>
			<artifactId>protostuff-runtime</artifactId>
			<version>1.1.3</version>
		</dependency>

代码:

序列化对象User类:

package com.java.protostuff.dyuproject;

import lombok.Data;

@Data
public class User {
	private String name;
    private int age;
}

序列化工具类:

package com.java.protostuff.dyuproject;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.runtime.RuntimeSchema;

public class UserSerializationUtil {
	 private static RuntimeSchema<User> schema = RuntimeSchema.createFrom(User.class);

	    /**
	     * 序列化方法,将User对象序列化为字节数组
	     * @param user
	     * @return
	     */
	    public static byte[] serialize(User user) {
	        return ProtostuffIOUtil.toByteArray(user, schema, LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
	    }

	    /**
	     * 反序列化方法,将字节数组反序列化为User对象
	     * @param array
	     * @return
	     */
	    public static User deserialize(byte[] array) {
	        User user = schema.newMessage();
	        ProtostuffIOUtil.mergeFrom(array, user, schema);
	        return user;
	    }
}

测试类:

package com.java.protostuff.dyuproject;

public class Test {

	public static void main(String[] args) {
		// 创建User对象
        User user = new User();
        user.setName("dyuproject");
        user.setAge(20);
        System.out.println("序列化前:" + user);
        // 使用UserSerializationUtil将user对象序列化
        byte[] userBytes = UserSerializationUtil.serialize(user);
        // 使用UserSerializationUtil反序列化字节数组为user对象
        User user2 = UserSerializationUtil.deserialize(userBytes);
        System.out.println("序列化后再反序列化:" + user2);
        // 判断值是否相等
        System.out.println(user.toString().equals(user2.toString()));

	}

}

总结:protostuff比protobuf使用起来简单很多。

参考文档:https://code.google.com/archive/p/protostuff/

                  https://github.com/protostuff/protostuff

                 https://protostuff.github.io/docs/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值