I have a proto file similar to this.
syntax = "proto3";
package proto;
import "github.com/gogo/protobuf/gogoproto/gogo.proto";
import "google/protobuf/struct.proto";
message JobCreateRequest {
string Name = 1 [(gogoproto.jsontag) = "name", (gogoproto.moretags)= "validate:\"required,max=100\""];
string Description = 2 [(gogoproto.jsontag) = "description", (gogoproto.moretags) = "validate:\"required,max=100\""];
google.protobuf.Value Data = 3 [(gogoproto.jsontag) = "data", (gogoproto.moretags) = "validate:\"required\""];
}
I am trying to unmarshal below json into protobuf using "encoding/json" library:
{
"name": "India",
"description": "test job",
"data": {
"id": 1
}
}
The code to decode request json to protobuf is:
json.NewDecoder(r.Body).Decode(req)
But the resulting Data field inside JobCreateRequest struct is always set to nil. What is the right way to use struct Value in protobuf?
If you use google.golang.org/protobuf, then you can use google.golang.org/protobuf/encoding/protojson
to convert.
req := &proto.JobCreateRequest{}
err := protojson.Unmarshal(bytes, req)
You can use github.com/golang/protobuf/jsonpb to convert JSON to protobuf.
req := proto.JobCreateRequest{}
jsonpb.Unmarshal(r.Body, &req)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With