Skip to content

Commit 84f98c7

Browse files
authored
fix: record MarshalJSON in case of default record with nullable field (#451)
1 parent a6c674d commit 84f98c7

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

schema.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,13 @@ import (
1616
jsoniter "github.com/json-iterator/go"
1717
)
1818

19-
var nullDefault = struct{}{}
19+
type nullDefaultType struct{}
20+
21+
func (nullDefaultType) MarshalJSON() ([]byte, error) {
22+
return []byte("null"), nil
23+
}
24+
25+
var nullDefault nullDefaultType = struct{}{}
2026

2127
var (
2228
schemaReserved = []string{

schema_test.go

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -416,6 +416,11 @@ func TestRecordSchema_ValidatesDefault(t *testing.T) {
416416
schema: `{"type":"record", "name":"test", "namespace": "org.hamba.avro", "fields":[{"name": "a", "type": {"type":"record", "name": "test2", "fields":[{"name": "b", "type": "int"},{"name": "c", "type": "int", "default": 1}]}, "default": {"b": 1}}]}`,
417417
wantErr: assert.NoError,
418418
},
419+
{
420+
name: "Record With Nullable Field",
421+
schema: `{"type":"record", "name":"test", "namespace": "org.hamba.avro", "fields":[{"name": "a", "type": {"type":"record", "name": "test2", "fields":[{"name": "b", "type": "int"},{"name": "c", "type": ["null","int"]}]}, "default": {"b": 1, "c": null}}]}`,
422+
wantErr: assert.NoError,
423+
},
419424
{
420425
name: "Record Not Map",
421426
schema: `{"type":"record", "name":"test", "namespace": "org.hamba.avro", "fields":[{"name": "a", "type": {"type":"record", "name": "test2", "fields":[{"name": "b", "type": "int"},{"name": "c", "type": "int", "default": 1}]}, "default": "test"}]}`,
@@ -438,9 +443,19 @@ func TestRecordSchema_ValidatesDefault(t *testing.T) {
438443
t.Run(test.name, func(t *testing.T) {
439444
t.Parallel()
440445

441-
_, err := avro.ParseWithCache(test.schema, "", &avro.SchemaCache{})
446+
schema, err := avro.ParseWithCache(test.schema, "", &avro.SchemaCache{})
442447

443448
test.wantErr(t, err)
449+
if err != nil {
450+
return
451+
}
452+
453+
// Ensure MarshalJSON Generate the same schema as it considers default values
454+
b, err := schema.(*avro.RecordSchema).MarshalJSON()
455+
assert.NoError(t, err)
456+
schema2, err := avro.ParseWithCache(string(b), "", &avro.SchemaCache{})
457+
assert.NoError(t, err)
458+
assert.Equal(t, schema, schema2)
444459
})
445460
}
446461
}

0 commit comments

Comments
 (0)