Thursday, May 6, 2010

I am working on an application and experimenting with Google Protocol Buffers. The idea is the back end service communication will use Protocol Buffers but I have some components which will be accessed by a service on the web.

I searched around on Google and found a few references from Google engineers stating that it would not be difficult to convert Protocol Buffers to JSON or the other way around as well as references hinting that this is how Google Maps works but I could not find any code for it.

I did find a JavaScript library that is supposed to encode and decode the binary format but it did not really make sense to me to go this route on the front end since the HTTP request still has a lot of text in it and the savings of binary encoding for most HTTP requests seems minimal. Anyway JavaScript does not really seem to be suited for reading and writing binary protocols. Add to that the fact that the library did not even have solid release and it was time to roll my own converter.

Mainly I just wanted to reuse the object models I create in my .proto files on the front end with those I use on the back end and this was the best way I could think of to do this. I have included below the code I came up with which works for my needs. I did not implement for all cases but if it is useful to your project the code is all there to improve on.

I should mention this uses a library for Java from "JSON.org". The models were just generated from my .proto files using protoc.

Anyway without further ado here is the code. If you make any improvements on this or have ideas on how to improve it please let me know. One other word of explanation the protocol class here if for my application the important part is the "decodeMessage" and "encodeMessage" part so I have removed some of the irrelevant parts from this.