Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to unmarshal json to protobuf struct field

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?

like image 549
Saurav Prakash Avatar asked Dec 24 '22 03:12

Saurav Prakash


2 Answers

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)
like image 156
binderclip Avatar answered Jan 04 '23 04:01

binderclip


You can use github.com/golang/protobuf/jsonpb to convert JSON to protobuf.

req := proto.JobCreateRequest{}
jsonpb.Unmarshal(r.Body, &req)
like image 44
mattes Avatar answered Jan 04 '23 03:01

mattes