Deserializing json to protobufs

331 views
Skip to first unread message

Francisco Ferreira

unread,
Jan 16, 2013, 8:54:07 AM1/16/13
to googl...@googlegroups.com
Hi, before posting I have tried the same question on stackoverflow. Here is the link: http://stackoverflow.com/questions/14357608/how-to-build-a-protocol-buffer-message-from-a-json-using-gson#comment19963016_14357608

I am currently stuck with: com.google.protobuf.LazyStringList field Helper$...etc...PROTOBUFFMESSAGE$Builder.thisIsAList_ to java.util.ArrayList and I have no idea how to make this work (without doing a major refractor on my code)

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Bellow is a copy paste from the question on stackoverflow:

I've been trying to generate protocol buffer messages from a json string using gson. Does anyone know how if it is possible to do it?

I have already tried:

Gson gson = new Gson();
Type type = new TypeToken<List<PROTOBUFFMESSAGE.Builder>>() {}.getType();
List<PROTOBUFFMESSAGE.Builder> list = (List<PROTOBUFFMESSAGE.Builder>) gson.fromJson(aJsonString, type);

and

Gson gson = new Gson();
Type type = new TypeToken<List<PROTOBUFFMESSAGE>>() {}.getType();
List<PROTOBUFFMESSAGE> list = (List<PROTOBUFFMESSAGE>) gson.fromJson(aJsonString, type);

The message inside the json uses the same names as in the protocol buffer i.e:

message PROTOBUFFMESSAGE {
   optional string this_is_a_message = 1;
   repeated string this_is_a_list = 2;
}

will lead to a json:

[
    {
        "this_is_a_message": "abc",
        "this_is_a_list": [
            "123",
            "qwe"
        ]
    },
    {
        "this_is_a_message": "aaaa",
        "this_is_a_list": [
            "foo",
            "bar"
        ]
    }
]

Although a list with the correct number of PROTOBUFFMESSAGE gets generated, they contain all their fields to null, so I'm not sure if this is a problem with the mapping, the reflection system not detecting protobuffs fields or something else. If anyone know how to do this it would be great. Btw I'm talking about java here.

EDIT:

changing the names in the json to:

        {
            "thisIsAMessage_": "abc",
            "thisIsAList_": [
                "123",
                "qwe"
            ]
        }

Makes the de serialization happen. And it does work except for the list that throws:

java.lang.IllegalArgumentException: Can not set com.google.protobuf.LazyStringList
Reply all
Reply to author
Forward
0 new messages