Golang使用proto3协议导致零值字段不显示
问题描述
proto协议生成的结构体如果使用直接转成json会导致零值字段不显示,这样的json是有毛病的,可以使用如下方法解决
示例Demo
package main
import (
"./pb"
"bytes"
"encoding/json"
"fmt"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
)
func main() {
var i int32 = 0
test(i)
}
func test(t int32) {
d := &pb.FrameD6 {
Datetimehour: "2020033014",
Recordcnt: t,
}
str,_ := json.Marshal(d)
s := TransProtoToJson(d)
fmt.Printf("@@@--incorrect JSON---> %+v
",string(str))
fmt.Printf("@@@--correct JSON---> %+v
",s)
}
func TransProtoToJson (pb proto.Message) string{
var pbMarshaler jsonpb.Marshaler
pbMarshaler = jsonpb.Marshaler{
EmitDefaults: true,
OrigName: true,
EnumsAsInts: true,
}
_buffer := new(bytes.Buffer)
_ = pbMarshaler.Marshal(_buffer, pb)
return string(_buffer.Bytes())
}
运行结果
@@@--incorrect JSON---> {"datetimehour":"2020033014"}
@@@--correct JSON---> {"recordid":"","laneid":"","programver":"","datetimehour":"2020033014","recordcnt":0,"moneycnt":0,"companyid":"","parkid":""}