Converting Protocol Buffers data to Json and back with Gson Type Adapters

Alexander Moses
4 min readFeb 13, 2019

Introduction

In this article, I will demonstrate to the reader a method to write a GSON Type Adapter for converting protobuf objects to and from JSON.

Why write an adapter ?

GSON does not deserialize protobuf objects out-of-the-box. There are no classes or utilities in GSON that convert data represent as protobuf data to JSON and vice versa.

However, we do have the option of using JsonFormat class which can be used for achieving our purpose.

Why not use JsonFormat directly ?

In my case, my application was already reading data in JSON and deserializing it to the respective POJO’s. However, a change in the direction of the project meant that new classes would have to be modeled using Google’s Protocol Buffers. Protobuf was great but it had the following shortcomings:

  • Maintenance: Editing protobuf was difficult. There is a lack of text editors with plugins that support read, display and editing of protobuf data. In contrast, editing JSON data was really simple. A lot of editors such as Atom provide plugins which made it easy to read and update JSON data.
  • Program Design: Our app used a single GSON instance for our data. We needed a way to use that same GSON instance to read data represented as protocol buffers.

Let the Example Begin :)

--

--