How to achieve the following with protojson package in Golang?
Protobuf:
type ProtoResp struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Xesp isActionResponse_Xesp `protobuf_oneof:"xesp"`
TimeTakena string `protobuf:"bytes,9,opt,name=time_takena,json=timeTakena,proto3" json:"time_takena,omitempty"`
}
So, I need to marshal the array of proto into a json. For example,
var protoResps []ProtoResp
How do I marshal this protoResps?
Currently, protojson.Marshal function can marshal ProtoResp but can't marshal []ProtoResp as its slice of proto.
I also need to unmarshal this later back into []ProtoResp
Thanks in advance.
I guess
json.Marshal(protoResps)does not work for you because the document forprotojsonstates:One workaround is still to utilize the
encoding/json, but marshal/unmarshal each item with theprotojsonpakcage.Option 1: Implement
json.Marshalerandjson.UnmarshalerIf
ProtoRespis a local type, modify it to implement theMarshalerandUnmarshalerinterfaces:Then it's safe to use the
encoding/jsonpackage to marshal/unmarshal[]*ProtoResp(an instance ofProtoRespshould not be copied, most of the time, you want to hold a pointer instead. I will use*ProtoRespfrom now on).Option 2: Use
json.RawMessageto delay the encoding/decodingIf
ProtoRespis not a local type, a workaround is to usejson.RawMessageto delay the encoding/decoding. This approach consumes more memory.