简体   繁体   English

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

[英]Converting composed objects to json in Go

I am new to Go and am unsure about how to approach this problem. 我是Go的新手,不确定如何解决此问题。 In OOP terms, I have a base class of Animal and two subclasses of Cat and Dog. 用OOP术语来说,我有动物的基类和猫和狗的两个子类。 I want to specify a ToJson method for Animal which will work for all animals. 我想为Animal指定一个ToJson方法,该方法适用于所有动物。

My problem is that when I call dog.ToJson() I only get the Dog properties of dog and none of the Animal properties. 我的问题是,当我调用dog.ToJson()时,我只获得dog的Dog属性,而没有Animal属性。

How can I make ToJson work as expected (ie with recursion )? 如何使ToJson正常工作(即使用递归 )?

edit: Changed code to reflect suggestions in answer by lbonn, which I could not get to work how I want it to. 编辑:更改代码以反映lbonn回答中的建议,但我无法按照我的意愿进行工作。 edit2: consistency in question following code change edit2:代码更改后问题的一致性

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. 匿名字段的Json编码已从go 1中删除。希望它会在go 1.1中恢复。 See https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/jYMHbEv44r4 for more details. 有关更多详细信息,请参见https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/jYMHbEv44r4

So the best you can get with the standard library right now (with go 1) is http://play.golang.org/p/LncNFeN8ys 因此,现在就可以通过标准库(执行1)获得的最好成绩是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. 在发布1.1版之前,您始终可以使用skelterjohn的补丁程序https://github.com/skelterjohn/json/支持匿名字段。

Or use tip, installing from source that has this issue fixed. 或使用提示,从已解决此问题的源安装。 see https://codereview.appspot.com/6460044 参见https://codereview.appspot.com/6460044

Here, the ToJson method applies to the anonymous field Animal of Dog . 在这里, ToJson方法适用于匿名字段Animal of Dog The call d.ToJson is only a visibility shortcut to d.Animal.ToJson . 呼叫d.ToJson只是一个知名度捷径d.Animal.ToJson GoLang Tutorials: Anonymous fields in struct GoLang教程:struct中的匿名字段

Here, I would write a function instead of a method (a simple wrapper around Marshal ): 在这里,我将编写一个函数而不是一个方法(围绕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. 更普遍地说,go中没有真正的继承概念。 The object paradigm used in the language is quite different from mainstream OOP, like in Java or C++. 该语言中使用的对象范式与主流的OOP(例如Java或C ++)完全不同。 The Go FAQ provides some good clarifications about it. Go常见问题解答对此提供了一些很好的说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM