diff --git a/unmarshal.go b/unmarshal.go index c5b63d1..ec6a38a 100644 --- a/unmarshal.go +++ b/unmarshal.go @@ -131,7 +131,7 @@ func unmarshalResourceObjects(ros []*resourceObject, v any, m *Unmarshaler) erro } // allocate an empty slice of the outType if there are no resource objects to unmarshal, - // because the main loop cannot construct run and construct one. + // because the main loop cannot construct one. if len(ros) == 0 { outValue = reflect.MakeSlice(outType, 0, 0) } @@ -253,8 +253,11 @@ func (ro *resourceObject) unmarshalFields(v any, m *Unmarshaler) error { continue } relDocument, ok := ro.Relationships[name] - if !ok || relDocument.isEmpty() { - // relDocument has no relationship data, so there's nothing to do + if !ok { + continue + } + if !relDocument.hasMany && relDocument.isEmpty() { + // ensure struct field is nil for data:null cases only (we want empty slice for data:[]) continue } diff --git a/unmarshal_test.go b/unmarshal_test.go index 484d566..463d04b 100644 --- a/unmarshal_test.go +++ b/unmarshal_test.go @@ -299,7 +299,7 @@ func TestUnmarshal(t *testing.T) { expect: &ArticleRelated{}, expectError: ErrRelationshipMissingRequiredMembers, }, { - // this test verifies that relationship data objects that are null or [] unmarshal + // verifies for empty relationship data: null -> nil and [] -> []Type{} description: "*ArticleRelated empty relationships data (valid)", given: articleRelatedNoOmitEmptyBody, do: func(body []byte) (any, error) { @@ -307,7 +307,7 @@ func TestUnmarshal(t *testing.T) { err := Unmarshal(body, &a) return &a, err }, - expect: &ArticleRelated{ID: "1", Title: "A"}, + expect: &ArticleRelated{ID: "1", Title: "A", Author: nil, Comments: []*Comment{}}, expectError: nil, }, { // this test verifies that empty relationship data objects do not unmarshal