2

我有 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;
}

我可以使用以下方法创建模型并将其序列化为 JSON JsonFormat.printer().print(...)

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);

而且似乎也没有办法将 an 传递ExtensionRegistryJsonFormat.parser()任何一个。

有没有办法让这个Protobuf → JSON → Protobuf序列化/反序列化链工作?

4

1 回答 1

0

显然JsonFormat的解析器不支持扩展

于 2017-12-21T07:23:59.637 回答