Is anyone familiar with a stable C++ solution (library, code snippet etc.) which converts protobuf messages to/from JSON?
Asked
Active
Viewed 3.4k times
24
-
2protobuf messages *by themselves* don't really have enough info for that; I would just deserialize into an object model (protobuf), and the serialize (your choice of json engine) that... I don't use C++ though, so I don't know the exact options available there (it is a breeze with protobuf-net, but : different platform) – Marc Gravell Aug 10 '11 at 09:11
-
1Thank you very much for the idea, Marc. It would definitely save a lot of time. I'm also considering to try protobuf's reflection mechanism. Hopefully one of the approaches will work :) – Zaur Nasibov Aug 10 '11 at 09:58
-
1I think that using protobuf's reflection mechanism is a good approach to make a generic JSON serializer/parser from JSON to protobuf generated types. I've made something like this, but to CORBA IDL generated types in http://code.google.com/p/corbasim/ – Andrés Senac Oct 05 '11 at 11:04
-
See also https://stackoverflow.com/q/2544580/545127 – Raedwald Dec 12 '17 at 17:21
-
3protobuf v3 supports JSON, see https://stackoverflow.com/a/44291335/757777 – Erik Sjölund Dec 27 '17 at 08:26
-
1I think this thread does not deserve to be closed, as it could be precious as information. – lrleon Jan 11 '21 at 20:16
4 Answers
8
This one is better IMO: https://github.com/shramov/json2pb
it does conversion in both directions and handles extensions

haberlerm
- 81
- 1
- 2
5
-
This one did the trick for me. I tried `json2pb`first and had throuble getting it to work (and found little in the way of documentation). I didn't have much trouble getting this `pbjson` tool working with their test example, and I found that it took only a minor effort to edit their test driver to parse my data. – arr_sea Oct 30 '19 at 21:28
-
By the way, for what it's worth, the author of this `pbjson` tool says they drew inspiration from `pb2json`. – arr_sea Oct 30 '19 at 21:29
3
I've made a bootstrap implementation of a JSON parser for protobuf generated types, using the its reflection mechanism, and adapting the parse I've made previously for CORBA IDL generated types.
You can find it at http://corbasim.googlecode.com/svn/trunk/protobuf2json_exported.zip
By this way for each protobuf defined message, you will be able to parse its instances by doing:
Foo foo;
const std::string json_foo = "{\"text\": \"Hello world\"}";
protobuf2json::json::parse(foo, json_foo);
It's just an initial implementation, and it just support string fields, but it's easy to implement all kind of fields.

Andrés Senac
- 841
- 6
- 14