我很难将 JSON 解组为 protobuf 生成的结构。 我有以下 JSON 数据: [ { "name": "C1", "type": "docker" }, { "name": "C2", "type": "docker" } ] 我已经像这样建模了我的 protobuf 定义: syntax = "proto3"; package main; message Container { string name = 1; string type = 2; ...
log.Fatalf("Error marshaling protobuf to JSON: %v", err) } fmt.Printf("Deserialized JSON: %s\n", string(deserializedJSON)) } 在这个例子中,首先定义了一个与 Protobuf 消息对应的 JSON 结构体PersonJSON。然后,使用json.Unmarshal将 JSON 字符串解码到这个结构体中。接着,将这个结构体转换为 Protobu...
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` Age int32 `protobuf:"varint,2,opt,name=age,proto3" json:"age,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } 1. 2. 3. 4...
jsonendtimestamp:=strconv.FormatInt(time.Now().UTC().UnixNano(), 10) jsonendint,_:=strconv.Atoi(jsonendtimestamp) fmt.Println("===END===",jsonendint) protobufbegintimestamp:=strconv.FormatInt(time.Now().UTC().UnixNano(), 10) protobufbeginint,_:=strconv.Atoi(protobufbegintimestamp...
fmt.Println("json:",jsonendint-jsonbeginint) fmt.Println("gob:",gobendint-gobbeginint) fmt.Println("protobuf:",protobufendint-protobufbeginint) 尝试了100,1000,10000,100000次的序列化对比时间: 总结: 总体来说protobuf的效率最高,gob的效率比json的还要低。
JSON与Protobuf都可以用来信息交换,JSON是一种简单的消息格式,以文本方式传输,而Protobuf是以二进制方式进行传输,相较于JSON消息体积会有明显的缩小,所以传输速度也比JSON快。除此之外,Protobuf不仅仅是一种用于交换的消息格式,还是用于定义交换消息的规则和工具,目前基本支持所有的主流语言。
state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` Male bool `protobuf:"varint,2,opt,name=male,proto3" json:"male,omitempty"` ...
在Golang中,我们可以使用官方提供的protobuf库来实现protobuf的编码和解码。首先需要使用protobuf定义语言(Protocol Buffers Language)来定义数据结构和消息格式,然后使用protoc编译器将定义文件转换为Golang代码,生成的代码中包含了相应的数据结构和方法,可以用于序列化和反序列化。
message 类似golang中的struct type User struct { Name stringprotobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"Age int32protobuf:"varint,2,opt,name=age,proto3" json:"age,omitempty"XXX_NoUnkeyedLiteral struct{}json:"-"XXX_unrecognized []bytejson:"-"XXX_sizecache int32json:"-...
// 定义数据结构,message 类似golang中的structtypeUserstruct{Namestring`protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`Ageint32`protobuf:"varint,2,opt,name=age,proto3" json:"age,omitempty"`XXX_NoUnkeyedLiteralstruct{}`json:"-"`XXX_unrecognized[]byte`json:"-"`XXX_sizecache...