json.Marshal回归奇怪的结果

时间:2014-01-24 22:12:47

标签: json go

我正在尝试将go结构转换为JSON。我以为我知道该怎么做,但我对这个程序的输出感到困惑。我错过了什么?

package main
import "fmt"
import "encoding/json"

type Zoo struct {                                                                       
    name string
    animals []Animal
}
type Animal struct {
    species string
    says string
}

func main() {
    zoo := Zoo{"Magical Mystery Zoo",                                                   
         []Animal {
            { "Cow", "Moo"},
            { "Cat", "Meow"},
            { "Fox", "???"},
        },
    }
    zooJson, err := json.Marshal(zoo)
    if (err != nil) {
        fmt.Println(err)
    }

    fmt.Println(zoo)
    fmt.Println(zooJson)
}

输出:

{Magical Mystery Zoo [{Cow Moo} {Cat Meow} {Fox ???}]}
[123 125]

预期产出(某事情如下):

{Magical Mystery Zoo [{Cow Moo} {Cat Meow} {Fox ???}]}
{
    "name" : "Magical Mystery Zoo",
    "animals" : [{
             "name" : "Cow",
             "says" : "moo"
         }, {
             "name" : "Cat",
             "says" : "Meow"
         }, {
             "name" : "Fox",
             "says" : "???"
         }
    ]
 }

[123 125]来自哪里?

感谢帮助!

2 个答案:

答案 0 :(得分:5)

编组的结果为[]byte,因此123125{}

的ascii

必须导出结构字段以便封送工作:

  

每个导出的struct字段都成为对象的成员

答案 1 :(得分:1)

您的问题在您的结构中未被导出(如果您需要,请将其称为非公开)字段。 Here is the example on Go Play如何修复它。

此外,如果您不喜欢JSON字段的命名方式(大多数情况下是大写字母),您可以使用struct标签更改它们(请参阅json.Marshal doc)。