Skip to content
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

Unexpected error from result.Decode() #16

Closed
kjk opened this issue Oct 6, 2014 · 1 comment
Closed

Unexpected error from result.Decode() #16

kjk opened this issue Oct 6, 2014 · 1 comment
Labels

Comments

@kjk
Copy link
Contributor

kjk commented Oct 6, 2014

This comes from trying to decode real facebook response, but this is a minimal test case:

package main

import (
    "encoding/json"
    "fmt"

    "github.com/huandu/facebook"
)

type Actions2 struct {
    Foo int
}

type Foo struct {
    Actions2 *Actions2
    Comment  int
}

func testDecode(sJson string) {
    var result facebook.Result
    err := json.Unmarshal([]byte(sJson), &result)
    if err != nil {
        fmt.Printf("json.Unmarshal() failed with %q\n", err)
        return
    }
    var v Foo
    err = result.Decode(&v)
    if err != nil {
        fmt.Printf("result.Decode() failed with %q\n", err)
        return
    }
    fmt.Printf("testDocode: ok!\n")
}

func main() {
    // this is ok
    sJson := `{
 "comment": 5
}`
    testDecode(sJson)

    // this fails
    sJson = `{
 "actions2": null,
 "comment": 5
}`
    testDecode(sJson)
}

The code fails with error reflect: call of reflect.Value.Type on zero Value when trying to decode actions2 when "actions2" field exists in json but is set to "null".

It doesn't happen when "actions2" field is completely missing.

@kjk
Copy link
Contributor Author

kjk commented Oct 6, 2014

Not sure if it covers all the bases, but the following change fixes the problem for me:

diff --git a/result.go b/result.go
index e6ef952..6c6eea7 100644
--- a/result.go
+++ b/result.go
@@ -309,7 +309,9 @@ func (res Result) decode(v reflect.Value, fullName string) error {
 }

 func decodeField(val reflect.Value, field reflect.Value, fullName string) error {
+       fieldIsPtr := false
        if field.Kind() == reflect.Ptr {
+               fieldIsPtr = true
                if field.IsNil() {
                        field.Set(reflect.New(field.Type().Elem()))
                }
@@ -321,6 +323,10 @@ func decodeField(val reflect.Value, field reflect.Value, fullName string) error
                return fmt.Errorf("field '%v' cannot be decoded. make sure the output value is able to be set.", fullName)
        }

+       if fieldIsPtr && !val.IsValid() {
+               return nil
+       }
+
        kind := field.Kind()
        valType := val.Type()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants