在Go中将组合对象转换为json

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.

My problem is that when I call dog.ToJson() I only get the Dog properties of dog and none of the Animal properties.

How can I make ToJson work as expected (ie with recursion)?

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

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}
}

Json encoding of anonymous fields was dropped from go 1. Hopefully it will be back in go 1.1. See https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/jYMHbEv44r4 for more details.

So the best you can get with the standard library right now (with go 1) is http://play.golang.org/p/LncNFeN8ys

You can always use skelterjohn's patch https://github.com/skelterjohn/json/ to support anonymous fields till go 1.1 is released.

Or use tip, installing from source that has this issue fixed. see https://codereview.appspot.com/6460044

Here, the ToJson method applies to the anonymous field Animal of Dog. The call d.ToJson is only a visibility shortcut to d.Animal.ToJson. GoLang Tutorials: Anonymous fields in struct

Here, I would write a function instead of a method (a simple wrapper around Marshal):

func ToJson(i interface{}) []byte {
    data,err := json.Marshal(i)
    if err != nil {
        panic("???")
    }
    return data
}

This is not specific to animals or dogs but it doesn't really need to.

More generally, there is no real notion of inheritance in go. The object paradigm used in the language is quite different from mainstream OOP, like in Java or C++. The Go FAQ provides some good clarifications about it.