title: Custom MarshalJSON() never gets called in Go
body: <p>I've written custom versions of <code>MarshalJSON</code> and <code>UnmarshalJSON</code>. My <code>UnmarshalJSON</code> gets called the way I want it to, but I can't get it to work with <code>MarshalJSON</code>. Here's code that summarizes my problem:</p>
  
  <pre><code>package main
  
  import (
      "bytes"
      "encoding/json"
      "fmt"
      "log"
      "os"
  )
  
  type myStruct struct {
      Data string `json:"data"`
  }
  
  func (s *myStruct) MarshalJSON() ([]byte, error) {
      return []byte(`{"data":"charlie"}`), nil
  }
  
  func (s *myStruct) UnmarshalJSON(b []byte) error {
      // Insert the string directly into the Data member
      return json.Unmarshal(b, &amp;s.Data)
  }
  
  func main() {
      // Create a struct with initial content "alpha"
      ms := myStruct{"alpha"}
  
      // Replace content with "bravo" using custom UnmarshalJSON() (SUCCESSFUL)
      if err := json.NewDecoder(bytes.NewBufferString(`"bravo"`)).Decode(&amp;ms); err != nil {
          log.Fatal(err)
      }
  
      // Use custom MarshalJSON() to get "charlie" back (UNSUCCESSFUL)
      if err := json.NewEncoder(os.Stdout).Encode(ms); err != nil {
          log.Fatal(err)
      }
  
      // Trying another method (UNSUCCESSFUL)
      if ret, err := json.Marshal(ms); err != nil {
          log.Fatal(err)
      } else {
          fmt.Println(string(ret))
      }
  
      // Verify that the Marshaler interface is correctly implemented
      var marsh json.Marshaler
      marsh = &amp;ms
      ret, _ := marsh.MarshalJSON()
      fmt.Println(string(ret)) // Prints "charlie"
  }
  </code></pre>
  
  <p>In short, the program encodes the <code>struct</code> "automatically" in two ways, and then finally calls <code>MarshalJSON</code> manually. The response I want is <code>"charlie"</code>. Running the code generates the following output:</p>
  
  <pre><code>{"data":"bravo"}
  {"data":"bravo"}
  {"data":"charlie"}
  </code></pre>
  
  <p>Try it at Go Playground: <a href="http://play.golang.org/p/SJ05S8rAYN">http://play.golang.org/p/SJ05S8rAYN</a></p>