给定以下 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)
关于java - 在 Java 中将 json 转换为动态生成的 protobuf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51981456/