atul ahire
atul ahire

Reputation: 187

How can I pass an object as a service response object using GRPC?

I am developing a Java GRPC service which accepts JSON input and is returning a JSON structure as a response object. Can I return a class object instead of converting it to JSON in the response?

Can I parse the returned object received on client side with Java? If so, how?

In case the service is returning multiple different response objects (classes), then how should I configure proto to handle those objects. for example Car, Bike, etc.?

Upvotes: 0

Views: 2630

Answers (1)

DazWilkin
DazWilkin

Reputation: 40136

gRPC defaults to using Protobufs for service and message definitions. One advantage to this default mechanism is that you can define services and messages using Protobufs and protoc will generate client and server language-specific bindings for both.

Any message format (eg JSON) can be used with gRPC but it's less common and more toil for the developer

Does your gRPC client's stub accept and return JSON?

Or are you using the canonical JSON encoding that facilitates JSON messages in/out?

If you're unfamiliar with it, see the Java gRPC intro.

I ask, because using this default flow, gives you language-specific types (classes|structs etc.) at both the client and the server.

Protobufs doesn't support generic types. You can use Oneof for e.g. Dog or Cat when you have a known list of types. You can encapsulate messages (envelope) using Any when the list of types is unknown or limitless and is analogous to java.lang.Object

One final note, even though protoc will generate Java classes when configured to do so, the recommendation is to wrap|map such generated classes into your own, application types. This is partly to not too tightly bind to them but it is also because there is some protobuf-specific functionality that you likely don't want surfaced.

So you will likely be mapping to|from various object types regardless of which underlying message format you use although protobufs on-the-wire binary format can be more efficient than JSON and marshalling to|from protobufs may be more efficient than JSON marshalling

Upvotes: 1

Related Questions