Skip to content

Commit 1f93a81

Browse files
rolanciaWKBae
authored andcommitted
Add IgnorePrefix to protojson.MarshalOptions
1 parent f520914 commit 1f93a81

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

encoding/protojson/encode.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ package protojson
77
import (
88
"encoding/base64"
99
"fmt"
10+
"strings"
1011

1112
"google.golang.org/protobuf/internal/encoding/json"
1213
"google.golang.org/protobuf/internal/encoding/messageset"
@@ -106,6 +107,10 @@ type MarshalOptions struct {
106107
// as JSON numbers instead of strings.
107108
EmitInt64sAsNumber bool
108109

110+
// IgnorePrefix is a prefix of the field names to ignore when marshaling.
111+
// If empty, no fields are ignored.
112+
IgnorePrefix string
113+
109114
// Resolver is used for looking up types when expanding google.protobuf.Any
110115
// messages. If nil, this defaults to using protoregistry.GlobalTypes.
111116
Resolver interface {
@@ -266,6 +271,10 @@ func (e encoder) marshalMessage(m protoreflect.Message, typeURL string) error {
266271
name = fd.TextName()
267272
}
268273

274+
if e.opts.IgnorePrefix != "" && strings.HasPrefix(name, e.opts.IgnorePrefix) {
275+
return true
276+
}
277+
269278
if err = e.WriteName(name); err != nil {
270279
return false
271280
}

encoding/protojson/encode_test.go

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2520,6 +2520,61 @@ func TestMarshal(t *testing.T) {
25202520
"optSint64": 3,
25212521
"optFixed64": 4,
25222522
"optSfixed64": 5
2523+
}`,
2524+
}, {
2525+
desc: "IgnorePrefix",
2526+
mo: protojson.MarshalOptions{IgnorePrefix: "sInt"},
2527+
input: &pb3.Scalars{
2528+
SBool: true,
2529+
SInt32: 1,
2530+
SInt64: 2,
2531+
SUint32: 3,
2532+
SUint64: 4,
2533+
SSint32: 5,
2534+
SString: "abc",
2535+
},
2536+
want: `{
2537+
"sBool": true,
2538+
"sUint32": 3,
2539+
"sUint64": "4",
2540+
"sSint32": 5,
2541+
"sString": "abc"
2542+
}`,
2543+
}, {
2544+
desc: "IgnorePrefix: json_name",
2545+
mo: protojson.MarshalOptions{IgnorePrefix: "foo"},
2546+
input: &pb3.JSONNames{
2547+
SString: "abc",
2548+
},
2549+
want: `{}`,
2550+
}, {
2551+
desc: "IgnorePrefix: not on map keys",
2552+
mo: protojson.MarshalOptions{IgnorePrefix: "-"},
2553+
input: &pb3.Maps{
2554+
Int32ToStr: map[int32]string{
2555+
-1: "a",
2556+
0: "b",
2557+
1: "c",
2558+
},
2559+
StrToNested: map[string]*pb3.Nested{
2560+
"-aa": {SString: "a"},
2561+
"bb": {SString: "b"},
2562+
},
2563+
},
2564+
want: `{
2565+
"int32ToStr": {
2566+
"-1": "a",
2567+
"0": "b",
2568+
"1": "c"
2569+
},
2570+
"strToNested": {
2571+
"-aa": {
2572+
"sString": "a"
2573+
},
2574+
"bb": {
2575+
"sString": "b"
2576+
}
2577+
}
25232578
}`,
25242579
}}
25252580

0 commit comments

Comments
 (0)