如何将原始的元素元帅到Golang的JSON?
如何使用Golang的Protojson软件包来实现以下内容?
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"`
}
所以,我需要将原始阵列元组纳入JSON。例如,
var protoResps []ProtoResp
我如何元使用此protoresps
?
当前,protojson.marshal
函数可以元帅protoresp
,但不能元帅[] Protoresp
作为其proto的切片。
我还需要稍后将其汇总到[] Protoresp
之前,
请提前。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我猜
json.marshal(protoresps)
对您不起作用,因为protojson的文档
状态:一个解决方法仍然是使用
编码/json
,但是使用protojson
pakcage元帅/删除每个项目。选项1:实现
json.marshaler
和json.unmarshaler
如果
protoresp
是一种本地类型,请修改以实现MARSHALER 和
unmarshaler
接口:然后,使用
编码/json
package to Marshal/unmarshal[]代码> protoresp
不应复制,大多数情况下,您要握住指针。则延迟编码/解码
选项2:使用
json.rawmessage
如果protoresp
不是本地类型, 延迟编码/解码。这种方法会消耗更多的内存。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.