java - 在 Java 中将 json 转换为动态生成的 protobuf

标签 java protobuf-java protocol-buffers

给定以下 json 响应:

{
    "id" : "123456",
    "name" : "John Doe",
    "email" : "john.doe@example.com"
}

以及以下user.proto 文件:

message User {
    string id = 1;
    string name = 2;
    string email = 3;
}

我希望有可能动态创建 protobuf 消息类(在运行时编译 .proto),这样如果 json 响应通过字段 "phone": "+1234567890" 我可以只上传新版本的 protobuf 文件以包含 string phone = 4 并在 protobuf 响应中公开该字段,而无需重新启动服务。

如果我要从帽子里提取这些类,我希望能够按照以下代码编写一些东西。

import com.googlecode.protobuf.format.JsonFormat;
import com.googlecode.protobuf.Message;
import org.apache.commons.io.FileUtils;

...

public Message convertToProto(InputStream jsonInputStream){
    // get the latest user.proto file
    String userProtoFile = FileUtils.readFileToString("user.proto");

    Message userProtoMessage = com.acme.ProtobufUtils.compile(userProtoFile);
    Message.Builder builder = userProtoMessage.newBuilderForType(); 
    new JsonFormat().merge(jsonInputStream, Charset.forName("UTF-8"), builder);
    return builder.build();
}

是否存在现有的 com.acme.ProtobufUtils.compile(...) 方法?或者如何实现?运行一个 protoc + load class 似乎有点矫枉过正,但如果没有其他选择,我愿意使用它......

最佳答案

您不能编译 .proto 文件(至少在 Java 中不能),但是您可以将 .proto 预编译为描述符 .desc

protoc --descriptor_set_out=user.desc user.proto

然后使用DynamicMessage 的解析器:

DynamicMessage.parseFrom(Descriptors.Descriptor type, byte[] data)

来源:google groups thread

关于java - 在 Java 中将 json 转换为动态生成的 protobuf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51981456/

相关文章:

java - 如何使用JUNIT测试ENUM

java - 如何对 SWT 列进行降序排序

java - 我在 'com/google/type/LatLng' 和 'com/google/protobuf/GeneratedMessage' 之间存在类型不匹配,并且无法说出原因

gradle - Gradle Protobuf任务未从依赖项中获取定义

protocol-buffers - 序列化消息中的换行符

java - 如何从数据库读取 keystore

java - 找不到给定名称的文件

java - gradle 的 Protobuf 插件不生成服务类

c - 在 c 中使用 nanopb 在 protobuf 中使用嵌套和重复字段的回调

go - 对 proto 文件使用共享的外部包?