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 forprotojson
states:One workaround is still to utilize the
encoding/json
, but marshal/unmarshal each item with theprotojson
pakcage.Option 1: Implement
json.Marshaler
andjson.Unmarshaler
If
ProtoResp
is a local type, modify it to implement theMarshaler
andUnmarshaler
interfaces:Then it's safe to use the
encoding/json
package to marshal/unmarshal[]*ProtoResp
(an instance ofProtoResp
should not be copied, most of the time, you want to hold a pointer instead. I will use*ProtoResp
from now on).Option 2: Use
json.RawMessage
to delay the encoding/decodingIf
ProtoResp
is not a local type, a workaround is to usejson.RawMessage
to delay the encoding/decoding. This approach consumes more memory.