protobuf序列化时丢失默认值字段的问题
1.问题的产生
在使用gin框架返回数据时,直接返回protobuf的message对象,如果message中存在某些属性为零值(即默认值,如 int类型的默认值为 0),那么在序列化时将会忽略这些零值字段,造成返回数据的字段丢失。
2.解决方法
如果直接返回message对象,那么在返回前进行如下解析即可
func TransProtoToJson(p proto.Message) map[string]interface{} {
var pbMarshaller jsonpb.Marshaler
pbMarshaller = jsonpb.Marshaler{
EmitDefaults: true,
OrigName: true,
EnumsAsInts: true,
}
_buffer := new(bytes.Buffer)
_ = pbMarshaller.Marshal(_buffer, p)
m := make(map[string]interface{})
_ = json.Unmarshal(_buffer.Bytes(), &m)
return m
}
经过解析之后就不会对零值字段进行忽略,但是将会引发一个新的问题,那就是message内int64类型的属性将会把值序列化为字符串类型,那么如何解决这个问题呢,目前而言我还没有找到解决方案,如果要严格按照格式进行返回,那么只能将protobuf的message对象转换为结构体再返回