protobuf

Plugins安裝Protobuf supportjava

build.gradle(application):android

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

build.gradle(app):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'
}

序列化:gradle

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();
    }
相關文章
相關標籤/搜索