Skip to content
This repository was archived by the owner on Sep 4, 2025. It is now read-only.

Commit 21b4945

Browse files
authored
Merge pull request #3 from msabramo/pr-99-make-nested-struct-ptr-work
Make nested struct pointers work
2 parents bb266b4 + 16e19ab commit 21b4945

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

request.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -555,6 +555,10 @@ func handlePointer(attribute interface{}, args []string, fieldType reflect.Type,
555555
concreteVal = reflect.ValueOf(&cVal)
556556
case uintptr:
557557
concreteVal = reflect.ValueOf(&cVal)
558+
case map[string]interface{}:
559+
var err error
560+
concreteVal, err = handleStruct(attribute, args, fieldType, fieldValue)
561+
return concreteVal.Elem(), err
558562
default:
559563
return reflect.Value{}, ErrUnsupportedPtrType(reflect.ValueOf(attribute), fieldType, structField)
560564
}

request_test.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -999,6 +999,52 @@ func sampleSerializedEmbeddedTestModel() *Blog {
999999
return blog
10001000
}
10011001

1002+
func TestUnmarshalNestedStructPtr(t *testing.T) {
1003+
type Director struct {
1004+
Firstname string `json:"firstname"`
1005+
Surname string `json:"surname"`
1006+
}
1007+
type Movie struct {
1008+
ID string `jsonapi:"primary,movies"`
1009+
Name string `jsonapi:"attr,name"`
1010+
Director *Director `jsonapi:"attr,director"`
1011+
}
1012+
sample := map[string]interface{}{
1013+
"data": map[string]interface{}{
1014+
"type": "movies",
1015+
"id": "123",
1016+
"attributes": map[string]interface{}{
1017+
"name": "The Shawshank Redemption",
1018+
"director": map[string]interface{}{
1019+
"firstname": "Frank",
1020+
"surname": "Darabont",
1021+
},
1022+
},
1023+
},
1024+
}
1025+
1026+
data, err := json.Marshal(sample)
1027+
if err != nil {
1028+
t.Fatal(err)
1029+
}
1030+
in := bytes.NewReader(data)
1031+
out := new(Movie)
1032+
1033+
if err := UnmarshalPayload(in, out); err != nil {
1034+
t.Fatal(err)
1035+
}
1036+
1037+
if out.Name != "The Shawshank Redemption" {
1038+
t.Fatalf("expected out.Name to be `The Shawshank Redemption`, but got `%s`", out.Name)
1039+
}
1040+
if out.Director.Firstname != "Frank" {
1041+
t.Fatalf("expected out.Director.Firstname to be `Frank`, but got `%s`", out.Director.Firstname)
1042+
}
1043+
if out.Director.Surname != "Darabont" {
1044+
t.Fatalf("expected out.Director.Surname to be `Darabont`, but got `%s`", out.Director.Surname)
1045+
}
1046+
}
1047+
10021048
func TestUnmarshalNestedStruct(t *testing.T) {
10031049

10041050
boss := map[string]interface{}{

0 commit comments

Comments
 (0)