无法将嵌套结构序列化为json

时间:2014-11-26 06:49:59

标签: go

我想将一个结构序列化为json,我写下面的代码,但总是返回空,没想出来。

您可以在此处尝试以下代码:http://play.golang.org/p/Y7Zv_aFbqs

package main

import (
    "encoding/json"
    "fmt"
    //"io/ioutil"
)

type Configitem struct {
    local_address string
    local_port    int
    method        string
    password      string
    server        string
    server_port   string
    timeout       int
}

type GuiConfig struct {
    configs []*Configitem
    index   int
}

func main() {

    item1 := &Configitem{
        local_address: "eouoeu",
        local_port:    111,
        method:        "eoeoue",
        password:      "ouoeu",
        server:        "oeuoeu",
        server_port:   "qoeueo",
        timeout:       3333,
    }

    config1 := &GuiConfig{
        index:   1,
        configs: []*Configitem{item1}}

    fmt.Println(config1.configs[0].local_address)

    res2, err := json.Marshal(config1)
    check(err)
    fmt.Println(string(res2))
}

func check(e error) {
    if e != nil {
        panic(e)
    }
}

总是返回{},我查了这个链接http://blog.golang.org/json-and-go,不知道为什么?我的代码有什么问题。

1 个答案:

答案 0 :(得分:3)

由于json.Marshal位于另一个包中,因此它只能访问导出的字段。如果您导出其有效的字段:http://play.golang.org/p/EMGm5-hs8g

您的另一个选择是自己实施MarshalJson界面(如果您不想导出字段):http://play.golang.org/p/9gGOBuGbVu