protobuf

Plugins安装Protobuf support

build.gradle(application):

dependencies {
       classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.8'
}

build.gradle(app):

apply plugin: 'com.google.protobuf'
android {    
    sourceSets {
        main {
            java {
                srcDir 'src/main/java'
            }
            proto {
                srcDir 'src/main/proto'
            }
        }
    }
}
protobuf {
    //配置protoc编译器
    protoc {
        artifact = 'com.google.protobuf:protoc:3.5.1'
    }
    //这里配置生成目录,编译后会在build的目录下生成对应的java文件
    generateProtoTasks {
        all().each { task ->
            task.builtins {
                remove java
            }
            task.builtins {
                java {}
            }
        }
    }
}

dependencies {
    implementation 'com.google.protobuf:protobuf-java:3.5.1'
}

序列化:

syntax = "proto3";

option java_package = "com.anny.protobuf";
option java_outer_classname = "_StudentSerializable";

message _Student{
    string name = 1;
    string sax = 2;
    int32 age = 3;

    repeated _Course course = 4;
}

message _Course{
    string name = 1;
    float score = 2;
}
/**
* protoBuf 用的是变长字节,会压缩数据
* 按需序列化,特别省空间
* 其他比如需要填满64位等
*/
    private static _StudentSerializable._Student deSerialize(byte[] bs) {
        try {
            return _StudentSerializable._Student.parseFrom(bs);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
        return null;
    }


    private static byte[] serialize() {
        _StudentSerializable._Course.Builder courseBuilder = _StudentSerializable._Course.newBuilder()
                .setName("English").setScore(66.6f);
        _StudentSerializable._Student.Builder builder = _StudentSerializable._Student.newBuilder()
                .setName("Anny").setAge(31).setSax("women").addCourse(courseBuilder);
        _StudentSerializable._Student student = builder.build();
        return student.toByteArray();
    }

 

posted @ 2020-04-06 21:14  Anny0920  阅读(188)  评论(0编辑  收藏  举报