Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert from Json to Protobuf?

I'm new to using protobuf, and was wondering if there is a simple way to convert a json stream/string to a protobuf stream/string in Java?

For example,

protoString = convertToProto(jsonString)

I have a json string that I want to parse into a protobuf message. So, I want to first convert the json string to protobuf, and then call Message.parseFrom() on it.

Thanks in advance for the help!

like image 529
Karan Tibrewal Avatar asked Jul 15 '16 23:07

Karan Tibrewal


People also ask

Does protobuf support JSON?

JSON is limited to certain python objects, and it cannot serialize every python object. Protobuf supports a wider range of data types when compared to JSON. For example, enumerations and methods are supported by Protobuf and not supported by JSON. JSON supports only a subset of python data types.

Is protobuf better than JSON?

JSON is usually easier to debug (the serialized format is human-readable) and easier to work with (no need to define message types, compile them, install additional libraries, etc.). Protobuf, on the other hand, usually compresses data better and has built-in protocol documentation via the schema.

Is protobuf lighter than JSON?

Protobuf messages were 9% smaller than JSON messages and they took only 4% less time to be available to the JavaScript code.


2 Answers

With proto3 you can do this using JsonFormat. It parses directly from the JSON representation, so there is no need for separately calling MyMessage.parseFrom(...). Something like this should work:

JsonFormat.parser().merge(json_string, builder);
like image 94
Adam Cozzette Avatar answered Oct 12 '22 18:10

Adam Cozzette


//You can use this for converting your input json to a Struct / any other Protobuf Class    

import com.google.protobuf.Struct.Builder;
import com.google.protobuf.Struct;
import com.google.protobuf.util.JsonFormat;
import org.json.JSONObject;

JSONObject parameters = new JSONObject();

Builder structBuilder = Struct.newBuilder();
JsonFormat.parser().merge(parameters.toString(), structBuilder);

// Now use the structBuilder to pass below (I used it for Dialog Flow V2 Context Management)
like image 34
Ayyub Kolsawala Avatar answered Oct 12 '22 18:10

Ayyub Kolsawala