title: Converting composed objects to json in Go
body: <p>I am new to Go and am unsure about how to approach this problem. In OOP terms, I have a base class of Animal and two subclasses of Cat and Dog. I want to specify a ToJson method for Animal which will work for all animals.</p>
  
  <p>My problem is that when I call dog.ToJson() I only get the Dog properties of dog and none of the Animal properties.</p>
  
  <p>How can I make ToJson work as expected (ie <a href="http://golang.org/pkg/encoding/json/#Marshal" rel="nofollow" title="with recursion">with recursion</a>)?</p>
  
  <p>edit: Changed code to reflect suggestions in answer by lbonn, which I could not get to work how I want it to.
  edit2: consistency in question following code change</p>
  
  <pre><code>package main
  
  import (
      "encoding/json"
      "fmt"
  )
  
  type Animal struct {
      Name string
  }
  
  type Cat struct {
      CatProperty int64
      Animal
  }
  
  type Dog struct {
      DogProperty int64
      Animal
  }
  
  func ToJson(i interface{}) []byte {
          data,err := json.Marshal(i)
      if err != nil {
          panic("???")
      }
      return data
  }
  
  func main() {
      dog := Dog{}
      dog.Name = "rex"
      dog.DogProperty = 2
      fmt.Println(string(ToJson(dog)))
      // Prints {"DogProperty":2}
      // I want it to print {"Name":"rex","DogProperty":2}
  }
  </code></pre>