How to convert a proto message to and from JSON (Java)?

41 views
Skip to first unread message

omid pourhadi

unread,
Sep 29, 2018, 5:32:47 AM9/29/18
to grpc.io


Hi,

I have a simple proto message in grpc

message Person{
  int32 id = 1;
  string firstName = 2;
}

How can I convert it into Json after generating code for java language and convert json to Person?

for example :


Person.toJson();

{"id":, "firstName": "test"}

Or

Person.fromJson(json);

let me know if there is any solution rather than https://grpc.io/blog/grpc-with-json

Thanks

Mahesh Kanote

unread,
Sep 29, 2018, 6:16:04 AM9/29/18
to omid pourhadi, grpc.io
Hi, 

I have been using this https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/util/Jsonformat. It is working for me to convert grpc messages to json and Jason to grpc message.

Thanks

--
You received this message because you are subscribed to the Google Groups "grpc.io" group.
To unsubscribe from this group and stop receiving emails from it, send an email to grpc-io+u...@googlegroups.com.
To post to this group, send email to grp...@googlegroups.com.
Visit this group at https://groups.google.com/group/grpc-io.
To view this discussion on the web visit https://groups.google.com/d/msgid/grpc-io/b8ef7c98-1eb3-4686-9006-8d8e33ef2258%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Mahesh Kanote

unread,
Sep 29, 2018, 6:19:23 AM9/29/18
to omid pourhadi, grpc.io

Carl Mastrangelo

unread,
Oct 1, 2018, 4:40:51 PM10/1/18
to grpc.io
Mahesh is right, that is the correct way.  

Also, I wrote the grpc-with-json article.  It was meant to show how to avoid any Protobuf dependencies.   If you want to use JsonFormat (which I also recommend), there is an example client and server here: https://github.com/grpc/grpc-java/tree/v1.15.0/examples/src/main/java/io/grpc/examples/advanced
Reply all
Reply to author
Forward
0 new messages