Android protobuf TextFormat、JsonFormat 序列化、反序列化

这篇博客介绍了如何使用Protocol Buffers(protobuf)在Java中进行序列化和反序列化操作。内容包括proto文件定义,Gradle配置,以及序列化和反序列化代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

proto

syntax = "proto2";

package com.seeyou.grpcdemo;

message Animal {
  optional string name = 1;
}

gradle 依赖

根目录 gradle
    dependencies {
        ...
        classpath "com.google.protobuf:protobuf-gradle-plugin:0.8.17"
    }
项目 gradle
plugins {
    ...
    id 'com.google.protobuf'
}

...

protobuf {
    protoc {
        artifact = "com.google.protobuf:protoc:3.19.2"
    }
    plugins {
        grpc {
            artifact = 'io.grpc:protoc-gen-grpc-java:1.47.0'
        }
    }
    generateProtoTasks {
        all().each { task ->
            task.builtins {
                java { option '' }
            }
            task.plugins {
                grpc { option '' }
            }
        }
    }
}


dependencies {
	...
    implementation 'io.grpc:grpc-okhttp:1.47.0'
    implementation 'io.grpc:grpc-protobuf:1.47.0'
    implementation 'io.grpc:grpc-stub:1.47.0'
    compileOnly 'org.apache.tomcat:annotations-api:6.0.53'
    implementation 'com.google.protobuf:protobuf-java-util:3.19.2'
}

java序列化、反序列化 代码

		TestService.Animal dog = TestService.Animal.newBuilder().setName("Dog").build();
        TestService.Animal.Builder dogBuild = TestService.Animal.newBuilder().setName("Dog");

        try {
            String s = TextFormat.printer().printToString(dog);//序列化 文本
            String print = JsonFormat.printer().print(dog);//序列话json
            TextFormat.merge(s, dogBuild); //text反序列化
            JsonFormat.parser().merge(print, dogBuild); //json反序列化
        } catch (Exception e) {
            e.printStackTrace();
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值