|
15 | 15 | // Mapper is the protoJSON mapper struct |
16 | 16 | Mapper struct { |
17 | 17 | reflectType reflect.Type |
| 18 | + optionalFields map[string]struct{} |
18 | 19 | protoMessageFields map[string]struct{} |
19 | 20 | regularFields map[string]struct{} |
20 | 21 | jsonFieldNames map[string]string |
@@ -43,6 +44,7 @@ func NewMapper(structInstance any) (*Mapper, error) { |
43 | 44 | reflectedValue := goreflect.GetDereferencedValue(structInstance) |
44 | 45 |
|
45 | 46 | // Prepare the different maps |
| 47 | + optionalFields := make(map[string]struct{}) |
46 | 48 | protoMessageFields := make(map[string]struct{}) |
47 | 49 | regularFields := make(map[string]struct{}) |
48 | 50 | jsonFieldNames := make(map[string]string) |
@@ -72,6 +74,11 @@ func NewMapper(structInstance any) (*Mapper, error) { |
72 | 74 | if err != nil { |
73 | 75 | return nil, err |
74 | 76 | } |
| 77 | + |
| 78 | + // Check if the field is optional |
| 79 | + if gostringsjson.IsJSONFieldOptional(jsonTag){ |
| 80 | + optionalFields[fieldName] = struct{}{} |
| 81 | + } |
75 | 82 |
|
76 | 83 | // Store the JSON field name |
77 | 84 | jsonFieldNames[fieldName] = jsonFieldName |
@@ -101,6 +108,7 @@ func NewMapper(structInstance any) (*Mapper, error) { |
101 | 108 | } |
102 | 109 | return &Mapper{ |
103 | 110 | reflectType: reflectedType, |
| 111 | + optionalFields: optionalFields, |
104 | 112 | protoMessageFields: protoMessageFields, |
105 | 113 | regularFields: regularFields, |
106 | 114 | jsonFieldNames: jsonFieldNames, |
@@ -161,6 +169,14 @@ func (m *Mapper) PrecomputeMarshalByReflection( |
161 | 169 |
|
162 | 170 | // Get the field value |
163 | 171 | fieldValueInterface := fieldValue.Interface() |
| 172 | + |
| 173 | + // Check if the field is optional and is nil |
| 174 | + if _, optionalOk := m.optionalFields[fieldName]; optionalOk { |
| 175 | + if fieldValue.IsNil() { |
| 176 | + // Skip nil optional fields |
| 177 | + continue |
| 178 | + } |
| 179 | + } |
164 | 180 |
|
165 | 181 | // Check if the field is a regular field |
166 | 182 | if _, regularOk := m.regularFields[fieldName]; regularOk { |
|
0 commit comments