Skip to content

Make nested struct pointers work #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 22, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions request.go
Original file line number Diff line number Diff line change
Expand Up @@ -542,6 +542,10 @@ func handlePointer(attribute interface{}, args []string, fieldType reflect.Type,
concreteVal = reflect.ValueOf(&cVal)
case uintptr:
concreteVal = reflect.ValueOf(&cVal)
case map[string]interface{}:
var err error
concreteVal, err = handleStruct(attribute, args, fieldType, fieldValue)
return concreteVal.Elem(), err
default:
return reflect.Value{}, ErrUnsupportedPtrType
}
Expand Down
46 changes: 46 additions & 0 deletions request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -946,6 +946,52 @@ func sampleSerializedEmbeddedTestModel() *Blog {
return blog
}

func TestUnmarshalNestedStructPtr(t *testing.T) {
type Director struct {
Firstname string `json:"firstname"`
Surname string `json:"surname"`
}
type Movie struct {
ID string `jsonapi:"primary,movies"`
Name string `jsonapi:"attr,name"`
Director *Director `jsonapi:"attr,director"`
}
sample := map[string]interface{}{
"data": map[string]interface{}{
"type": "movies",
"id": "123",
"attributes": map[string]interface{}{
"name": "The Shawshank Redemption",
"director": map[string]interface{}{
"firstname": "Frank",
"surname": "Darabont",
},
},
},
}

data, err := json.Marshal(sample)
if err != nil {
t.Fatal(err)
}
in := bytes.NewReader(data)
out := new(Movie)

if err := UnmarshalPayload(in, out); err != nil {
t.Fatal(err)
}

if out.Name != "The Shawshank Redemption" {
t.Fatalf("expected out.Name to be `The Shawshank Redemption`, but got `%s`", out.Name)
}
if out.Director.Firstname != "Frank" {
t.Fatalf("expected out.Director.Firstname to be `Frank`, but got `%s`", out.Director.Firstname)
}
if out.Director.Surname != "Darabont" {
t.Fatalf("expected out.Director.Surname to be `Darabont`, but got `%s`", out.Director.Surname)
}
}

func TestUnmarshalNestedStruct(t *testing.T) {

boss := map[string]interface{}{
Expand Down