Leave a Comment
Nullable fields in json generated from protobuf file
Table of Contents
Native support
With grpc v2 for go, protofile’s optional option is supported, so you don’t need to import proto extensions anymore and use things like google.protobuf.StringValue.
my.proto
message FeeView {
optional string name = 1 [json_name = "name"];
}
go mapper
var name *string
if fee.Name != nil {
name = &fee.Name
}
fee := &desc.FeeView{
Name: name,
}
Legacy way with extensions
Null for nil value
my.proto
import "google/protobuf/wrappers.proto";
message FeeView {
google.protobuf.StringValue name = 1 [json_name = "name"];
}
go mapper
import "github.com/gogo/protobuf/types"
var name *types.StringValue
if fee.Name != nil {
name = &types.StringValue{
Value: *fee.Name,
}
}
fee := &desc.FeeView{
Name: name,
}
Which will lead to this json response
{"translation_key":"a fee","name":null,"value":5,"style":"body","text_color":"grey","tag":null}
Omit a field with nil value
If you want to omit the field completely, you can use oneof approach
proto
message View {
oneof subtitle {
string oneof_string_subtitle = 1 [json_name = "subtitle"];
}
}
go mapper
var subtitle *desc.View_OneofStringSubtitle
if in.Subtitle != nil {
subtitle = &desc.View_OneofStringSubtitle{
OneofStringSubtitle: *in.Subtitle,
}
}
return &desc.View{
Subtitle: subtitle,
}
More info on json options for grpc — https://blog.bullgare.com/2020/07/complete-list-of-swagger-options-to-protobuf-file/
LEAVE A COMMENT
Для отправки комментария вам необходимо авторизоваться.