Skip to content

Commit e8c65fd

Browse files
committed
use custom marshal/unmarshal interfaces that can preserve marshaler/unmarshaler settings
1 parent e7d161e commit e8c65fd

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

jsonpb/jsonpb.go

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,22 @@ type Marshaler struct {
7474
OrigName bool
7575
}
7676

77+
// JSONPBMarshaler is implemented by protobuf messages that customize the
78+
// way they are marshaled to JSON. Messages that implement this should
79+
// also implement JSONPBUnmarshaler so that the custom format can be
80+
// parsed.
81+
type JSONPBMarshaler interface {
82+
MarshalJSONPB(*Marshaler) ([]byte, error)
83+
}
84+
85+
// JSONPBUnmarshaler is implemented by protobuf messages that customize
86+
// the way they are unmarshaled from JSON. Messages that implement this
87+
// should also implement JSONPBMarshaler so that the custom format can be
88+
// produced.
89+
type JSONPBUnmarshaler interface {
90+
UnmarshalJSONPB(*Unmarshaler, []byte) error
91+
}
92+
7793
// Marshal marshals a protocol buffer into JSON.
7894
func (m *Marshaler) Marshal(out io.Writer, pb proto.Message) error {
7995
writer := &errWriter{writer: out}
@@ -102,8 +118,8 @@ type wkt interface {
102118

103119
// marshalObject writes a struct to the Writer.
104120
func (m *Marshaler) marshalObject(out *errWriter, v proto.Message, indent, typeURL string) error {
105-
if jsm, ok := v.(json.Marshaler); ok {
106-
b, err := jsm.MarshalJSON()
121+
if jsm, ok := v.(JSONPBMarshaler); ok {
122+
b, err := jsm.MarshalJSONPB(m)
107123
if err != nil {
108124
return err
109125
}
@@ -537,8 +553,8 @@ func (u *Unmarshaler) UnmarshalNext(dec *json.Decoder, pb proto.Message) error {
537553
if err := dec.Decode(&inputValue); err != nil {
538554
return err
539555
}
540-
if jsu, ok := pb.(json.Unmarshaler); ok {
541-
return jsu.UnmarshalJSON([]byte(inputValue))
556+
if jsu, ok := pb.(JSONPBUnmarshaler); ok {
557+
return jsu.UnmarshalJSONPB(u, []byte(inputValue))
542558
}
543559
return u.unmarshalValue(reflect.ValueOf(pb).Elem(), inputValue, nil)
544560
}

0 commit comments

Comments
 (0)