将JSON转换为Java中动态生成的protobuf

13
{"name": "John", "age": 30, "city": "New York"}

给定以下json响应:

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

以下是user.proto文件:

Translated version:

And the following user.proto file:

--->

以下是user.proto文件:

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

我希望能够动态地创建protobuf消息类(在运行时编译.proto文件),这样如果json响应通过"phone" : "+1234567890"字段得到增强,我只需要上传一个包含string phone = 4的新版本protobuf文件,并且在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 + 加载类似乎有点繁琐,但如果没有其他选项,我愿意使用它...

1个回答

6

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

protoc --descriptor_set_out=user.desc user.proto

然后使用DynamicMessage的解析器:

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

来源: Google群组帖子

这是关于IT技术的话题。

只是想再确认一下,如果 byte[] 数据包含比 .proto 文件中最初描述的字段更多的字段,解析会失败吗? - noMAD

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接