Skip to content

encoding/json: MarshalJSON isn't called for fields of a non-pointer struct #7536

@gopherbot

Description

@gopherbot

by timothy.stranex:

$ go version
go version go1.2 darwin/amd64

Here is a link to a program on play.golang.org that demonstrates the problem.
http://play.golang.org/p/HXNEgYhZgE

For reference, this is the program:

-------
package main

import "encoding/json"
import "fmt"

type DecimalE8 int64

func (d *DecimalE8) MarshalJSON() ([]byte, error) {
    return []byte(fmt.Sprintf("%.8f", float64(*d) / 1e8)), nil
}

type Payment struct {
    Amount DecimalE8
}

func main() {
    var p Payment
    p.Amount = 123456789

    s1, _ := json.Marshal(p)
    fmt.Println(string(s1))

    s2, _ := json.Marshal(&p)
    fmt.Println(string(s2))
}
-------

The actual output from this program is:
{"Amount":123456789}
{"Amount":1.23456789}

The expected output is:
{"Amount":1.23456789}
{"Amount":1.23456789}

Basically it seems that DecimalE8.MarshalJSON isn't being used when the struct is passed
as a value to json.Marshal but it is used when it's passed as a pointer. I would expect
that DecimalE8.MarshalJSON be used in both cases.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions