【问题标题】:How do I convert json string to protobuf message object?如何将 json 字符串转换为 protobuf 消息对象?
【发布时间】:2016-11-04 06:48:20
【问题描述】:
message Example {
    enum State {
        Deleted = 1;
        Inactive = 2;
        Active = 4;
    }

    optional uint64 id                       = 1        [(gson_name) = "id"];
    optional uint64 state                    = 2        [(gson_name) = "state"];
    optional uint64 userId                   = 3        [(gson_name) = "uui"];
    optional sint32 marketId                 = 4        [(gson_name) = "m"];
    optional uint64 productId                = 5        [(gson_name) = "p"];
}

Json 字符串

v: String = {"m": 97, "state": 1, "uui": 1, "id": 1, "p": 1}

使用 json 调用转换失败。

gson.fromJson(v, classOf[Example])

例外 java.lang.NullPointerException

我不确定这是否是将 json 转换为生成的 proto 类的正确方法。有人可以告诉我我做错了什么,或者可能建议一些其他方法来实现这一点。我使用的是 protobuf 2.6 版,无法真正升级到该项目的 3。

【问题讨论】:

    标签: json scala gson protocol-buffers


    【解决方案1】:

    我假设您已经为 Message 对象生成了 Java 类。如果您在 OP 中为 Proto Message 生成了 Java 类,则可以使用以下代码。

    以下代码将 PROTO 消息写入文件。不需要的可以评论。

    将 JSON 转换为 protobuf 消息对象并写入文件的代码:-

    public static void main(String[] args) throws IOException {
    
            String jsonString = "{\"m\": 97, \"state\": 1, \"uui\": 1, \"id\": 1, \"p\": 1}";
    
            Gson gson = new GsonBuilder().create();
            JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
    
            ExampleProto.Example.Builder example = ExampleProto.Example.newBuilder();       
            example.setId(jsonObject.get("id").getAsLong());
            example.setMarketId(jsonObject.get("m").getAsInt());
            example.setProductId(jsonObject.get("p").getAsInt());
            example.setState(jsonObject.get("state").getAsInt());
            example.setUserId(jsonObject.get("uui").getAsInt());
    
            System.out.println(example.build());
    
            FileOutputStream output = new FileOutputStream(new File("proto.txt"));
            example.build().writeTo(output);
            output.close();
    
        }
    

    【讨论】:

    • 谢谢,但我希望将 json 反序列化为为我的 protobuf 消息生成的 java 类的对象。如果我必须转换为中间表示,我可能会使用 spray 的 json 库而不是 gson。
    • 不建议更改生成的 proto Java 类以添加注解来提及不同的属性名称。因此,使用属性名称解析 json 并将其映射到 PROTO java 类。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    • 2016-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多