java如何使用Gson从json构建协议缓冲区消息?
我一直在尝试使用gson从json字符串生成协议缓冲区消息。有人知道如何才能做到吗
我已经试过:
Gson gson = new Gson();
Type type = new TypeToken<List<PROTOBUFFMESSAGE.Builder>>() {}.getType();
List<PROTOBUFFMESSAGE.Builder> list = (List<PROTOBUFFMESSAGE.Builder>) gson.fromJson(aJsonString, type);
和
Gson gson = new Gson();
Type type = new TypeToken<List<PROTOBUFFMESSAGE>>() {}.getType();
List<PROTOBUFFMESSAGE> list = (List<PROTOBUFFMESSAGE>) gson.fromJson(aJsonString, type);
json中的消息使用与协议缓冲区中相同的名称,即:
message PROTOBUFFMESSAGE {
optional string this_is_a_message = 1;
repeated string this_is_a_list = 2;
}
将导致json:
[
{
"this_is_a_message": "abc",
"this_is_a_list": [
"123",
"qwe"
]
},
{
"this_is_a_message": "aaaa",
"this_is_a_list": [
"foo",
"bar"
]
}
]
虽然生成了一个PROTOBUFFMESSAGE数量正确的列表,但它们包含的所有字段都为null,因此我不确定这是否是映射问题,反射系统没有检测到protobuffs字段或其他问题。如果有人知道怎么做,那就太好了。顺便说一句,我这里说的是java
编辑:
将json中的名称更改为:
{
"thisIsAMessage_": "abc",
"thisIsAList_": [
"123",
"qwe"
]
}
使反序列化发生。除了抛出以下内容的列表外,它确实有效:
java.lang.IllegalArgumentException: Can not set com.google.protobuf.LazyStringList field Helper$...etc big path here...$PROTOBUFFMESSAGE$Builder.thisIsAList_ to java.util.ArrayList
# 1 楼答案
听起来您必须使用
GsonBuilder
来构建Gson
对象,并为com.google.protobuf.LazyStringList
对象写入和注册类型适配器# 2 楼答案
使用以下代码段,而不是通过构造函数启动
Gson
对象: