duanjiaolia97750 2012-12-29 03:49
浏览 229
已采纳

在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}
}
  • 写回答

2条回答

查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。