Skip to content

Latest commit

 

History

History
90 lines (65 loc) · 2.24 KB

File metadata and controls

90 lines (65 loc) · 2.24 KB

PBSerializer

Adds JSON as an alternate serialization method for Protobuf messages, on top of the regular protobuf API.

Dependencies

Build

You can build PBSerializer using CMake following these steps:

  1. Create a build dir in the root dir of the project mkdir build
  2. Inside the build dir, run CMake: cmake ..
  3. Finally, run make: make

This process will build both library and test suite. It is always a good idea to run the test suite before installing.

To run the test suie, inside the build dir, go to the test dir: cd tests And execute the tests program: ./tests

You can finally install the library running make install inside the build dir, not the tests dir

Usage

Wrap your protobuf-generated message type with PBSerializer<T> to get JSON (de)serialization on top of the regular protobuf-generated API:

#include "message.pb.h"
#include <pbserializer.h>

using namespace google::protobuf;

typedef PBSerializer<MyMessage> MyMessageJson;

MyMessageJson msg;
msg.set_id(42);
msg.set_name("Hello World!");

// Message -> JSON
std::string json;
msg.SerializeJsonToString(json);
// {"id":42,"name":"Hello World!"}

// JSON -> Message
MyMessageJson other;
other.ParseJsonFromString(json);

Streams work too, if you'd rather not go through a std::string:

std::ofstream out("message.json");
msg.SerializeJsonToOStream(out);

std::ifstream in("message.json");
other.ParseJSONFromIStream(in);

bytes fields: hex vs base64

Protobuf bytes fields hold raw binary data, which JSON strings can't. They are therefore encoded as text — hex by default, base64 optionally — by passing a BytesEncoding as the last argument to any of the serialize/parse methods above:

msg.SerializeJsonToString(json);                     // hex (default)
msg.SerializeJsonToString(json, BYTES_AS_BASE64);     // base64

other.ParseJsonFromString(json);                      // decodes as hex
other.ParseJsonFromString(json, BYTES_AS_BASE64);     // decodes as base64

The same encoding must be used on both ends — it is not auto-detected from the JSON — and it applies to every bytes field in the message, including nested messages.