我有2个Protobuf模型:
User
package demo;
option java_package = "com.stackoverflow.question";
option java_outer_classname = "UserModel";
message User {
message UserHeader {
required int64 userId = 1;
}
required UserHeader header = 1;
extensions 100 to 200;
}
Employee
import "person.proto";
package demo;
option java_package = "com.stackoverflow.question";
option java_outer_classname = "EmployeeModel";
extend demo.User {
optional EmployeeDetails details = 101;
}
message EmployeeDetails {
required string department = 1;
repeated Skill skills = 2;
}
message Skill {
required int64 id = 1;
required string name = 2;
}
我可以使用JsonFormat.printer().print(...)
创建模型并将其序列化为JSON:
ExtensionRegistry registry = ExtensionRegistry.newInstance();
EmployeeModel.registerAllExtensions(registry);
UserModel.User.Builder userBuilder = UserModel.User.newBuilder();
userBuilder.setHeader(UserModel.User.UserHeader.newBuilder().setUserId(1000));
EmployeeModel.EmployeeDetails.Builder employeeBuilder = EmployeeModel.EmployeeDetails.newBuilder();
employeeBuilder.setDepartment("Department 1")
.addSkills(EmployeeModel.Skill.newBuilder()
.setId(10_000)
.setName("Skill 10_0000")
.build())
.addSkills(EmployeeModel.Skill.newBuilder()
.setId(11_000)
.setName("Skill 11_0000")
.build());
userBuilder.setExtension(EmployeeModel.details, employeeBuilder.build());
final String json = JsonFormat.printer().print(userBuilder.build());
然而,将生成的JSON反序列化回Java对象失败了com.google.protobuf.InvalidProtocolBufferException: Cannot find field: details in message demo.User
:
UserModel.User.Builder userBuilder2 = UserModel.User.newBuilder();
JsonFormat.parser().merge(json, userBuilder2);
似乎也没有办法将ExtensionRegistry
传递给JsonFormat.parser()
。
有没有办法让 Protobuf→JSON→Protobuf 序列化/反序列化链工作?