【问题标题】:can not serialize a nested struct to json [duplicate]无法将嵌套结构序列化为 json [重复]
【发布时间】:2014-11-26 06:49:58
【问题描述】:

我想将一个结构序列化为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,不知道为什么?我的代码有什么问题。

【问题讨论】:

  • 是的,我做了一些搜索但还没有找到,谢谢提醒。

标签: go


【解决方案1】:

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

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

【讨论】:

  • 我认为现在是时候将这些作为重复项关闭了。这个“错误”现在每周会弹出几次。
  • o shoooooot,我今天才开始写,我忘了小写的意思是“私人”。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-20
相关资源
最近更新 更多