Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将json转换为Java中动态生成的protobuf_Java_Protocol Buffers_Protobuf Java_Google Protocol Buffer - Fatal编程技术网

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

将json转换为Java中动态生成的protobuf,java,protocol-buffers,protobuf-java,google-protocol-buffer,Java,Protocol Buffers,Protobuf Java,Google Protocol Buffer,给出以下json响应: { "id" : "123456", "name" : "John Doe", "email" : "john.doe@example.com" } 以及以下user.proto文件: 我希望能够动态创建protobuf消息类(在运行时编译一个.proto),这样,如果json响应通过一个字段“phone”得到增强,“+1234

给出以下json响应:

{
    "id" : "123456",
    "name" : "John Doe",
    "email" : "john.doe@example.com"
}
以及以下user.proto文件:

我希望能够动态创建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类似乎有些过分,但如果没有其他选择,我愿意使用它…

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

protoc --descriptor_set_out=user.desc user.proto
然后使用
动态消息
的解析器:

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

来源:

只是想再次检查,如果byte[]数据包含的字段比.proto文件中最初描述的字段多,解析会失败吗?
DynamicMessage.parseFrom(Descriptors.Descriptor type, byte[] data)