encoding/jsonpb: add AllowPartial option to MarshalOptions and UnmarshalOptions
Added tests related to required fields and AllowPartial. I somehow
missed this before.
Change-Id: I3eb17347b1f3a99be3d65af06c4549abcc87ae39
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/169701
Reviewed-by: Damien Neil <dneil@google.com>
diff --git a/encoding/jsonpb/encode.go b/encoding/jsonpb/encode.go
index b3a0a76..8e25183 100644
--- a/encoding/jsonpb/encode.go
+++ b/encoding/jsonpb/encode.go
@@ -28,6 +28,11 @@
type MarshalOptions struct {
pragma.NoUnkeyedLiterals
+ // AllowPartial allows messages that have missing required fields to marshal
+ // without returning an error. If AllowPartial is false (the default),
+ // Marshal will return error if there are any missing required fields.
+ AllowPartial bool
+
// If Indent is a non-empty string, it causes entries for an Array or Object
// to be preceded by the indent and trailed by a newline. Indent can only be
// composed of space or tab characters.
@@ -90,7 +95,7 @@
num := fd.Number()
if !knownFields.Has(num) {
- if fd.Cardinality() == pref.Required {
+ if !o.AllowPartial && fd.Cardinality() == pref.Required {
// Treat unset required fields as a non-fatal error.
nerr.AppendRequiredNotSet(string(fd.FullName()))
}