Search code examples
jsongostripe-paymentsmarshallingunmarshalling

Unmarshal data in Go using stripe library


Just started hacking with Go.

I'm trying to use the Stripe library. There is a type Charge which I am trying to use their custom UnmarshalJSON call, but no argument I pass seems to work. What's going on here?

var charge, err = sc.Charges.Get(id, nil)

if err != nil {
    log.Fatal(err)
}

thing := charge.UnmarshalJSON([]byte(charge))

Here's the function: https://github.com/stripe/stripe-go/blob/master/charge.go#L162

I receive: ./hello.go:48: cannot convert charge (type *stripe.Charge) to type []byte

Haven't found an argument to pass that will satisfy this function yet. Any help appreciated thanks.


Solution

  • JSON to Charge

    Charge.UnmarshalJSON() expects a byte slice ([]byte). Charge is a struct type, you can't convert a value of it (nor a pointer to it) to []byte. That's what the error message tells you.

    The byte slice that is expected by the UnmarshalJSON() method is a JSON text describing a Charge, or looking into the implementation of UnmarshalJSON(), it also accepts a single JSON text being the Charge ID.

    So this should work:

    var charge, err = sc.Charges.Get(id, nil)
    
    if err != nil {
        log.Fatal(err)
    }
    
    err := charge.UnmarshalJSON([]byte(`"123"`))
    

    Or a Charge struct represented in JSON (incomplete):

    var charge, err = sc.Charges.Get(id, nil)
    
    if err != nil {
        log.Fatal(err)
    }
    
    s := `{"id":"123","amount":2000,"description":"testing"}`
    err := charge.UnmarshalJSON([]byte(s))
    
    fmt.Printf("%+v", thing)
    

    Output should contain these fields properly set from the JSON text, amongst other fields having their zero values:

    {Amount:2000 Desc:testing ID:123}
    

    Charge to JSON

    To print a nicely formatted JSON representation of a Charge value, use json.Marshal():

    out, err := json.Marshal(c)
    if err != nil {
        panic(err) // handle error
    }
    fmt.Println(string(out))
    

    Or use json.MarshalIndent():

    out, err := json.MarshalIndent(c, "", "  ")
    if err != nil {
        panic(err) // handle error
    }
    fmt.Println(string(out))
    

    Example output (stripped):

    {
      "amount": 2000,
      "description": "testing",
      "id": "123",
    }