众所周知,golang的json库 有个 omitempty的tag ,有了它,这个json序列化的时候,如果这个字段是零值,则会忽略此字段的序列化,导致json字符串中没有对应的字符串。 这对于某些人是困惑的,一般默认是没有 omitempty 这个tag的,但是。 但是来了,但是protobuf 生成的pb.go 里面带有的jsontag 就默认是有omitempty的。
defmain(): argc =len(sys.argv) ifargc<2: print('usage:%s <xxx.go>'%sys.argv[0]) return f =open(sys.argv[1],'rb') ifnotf: print("open file error:%s"%sys.argv[1]) return s = f.read().decode('utf-8') f.close() s = s.replace(',omitempty','') # f =open(sys.ar...
正好也可以学习一下protobuf的使用 跟Json相比protobuf性能更高,更加规范 编解码速度快,数据体积小 使...
使用protobuf 官方的 go 插件得到的代码 type One struct { Type *uint32 `protobuf:"varint,1,req,name=type" json:"type,omitempty"` Value *uint32 `protobuf:"varint,2,req,name=value" json:"value,omitempty"` Size *uint32 `protobuf:"varint,3,req,name=size" json:"size,omitempty"` XXX_un...
typeCustomerResponsestruct{Idint64`json:"id"`Namestring`json:"name"`Phonestring`json:"phone,omitempty"`} 我在不赋值phone字段的时候返回json里就不会出现他,另外补充的一点就是,golang的string型和int型都没有null值,所以说当int为0,string为""的时候(默认值)的时候都不会去序列化这些变量。
Printf("%s :全部大写,并且使用json标记,因此序列化后自动使用json标记名称\n", string(data2)) fmt.Printf("%s :全部大写,并且使用json标记,增加omitempty标记,带有该标记的不赋值的情况\n", string(data3)) fmt.Printf("%s :全部大写,并且使用json标记,没有omitempty标记,上次字段依旧不赋值的情况\n", ...
参考golang 使用 protobuf 的教程( https://www.cnblogs.com/jkko123/p/7161843.html ),但是我生成的testCui.pb.go文件有一些XXX字段,然后Phone那个初始化就不行,但是Person可以 type Phonestruct{Type PhoneType `protobuf:"varint,1,opt,name=type,proto3,enum=testpb...
可以看到Code字段的json tag里的omitempty没有了,这时候如果我们再执行 msg := &MyMessage{Code: 0} bdata, _ := json.Marshal(msg) fmt.Println(string(bdata)) 这个代码片段,输出就是{"Code": 0}了。达到我们的目的了。当然inject_tag不仅仅可以设置json的tag,它可以设置任何的tag。 总结 protobuf的...
sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Name1 string `protobuf:"bytes,1,opt,name=name1,proto3" json:"name1,omitempty"` Q2 *Q1_Q2 `protobuf:"bytes,2,opt,name=q2,proto3" json:"q2,omitempty"` } 1. 2. ...
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:"-"` ...