Golang使用proto3协议导致零值字段不显示

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 \n",string(str))
	fmt.Printf("@@@--correct JSON---> %+v \n",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":""} 
posted @ 2020-04-01 20:15  Kingram  阅读(2482)  评论(0编辑  收藏  举报