无法将嵌套的结构体序列化为 JSON。

huangapple go评论97阅读模式
英文:

can not serialize a nested struct to json

问题

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

英文:

i want to serialize a struct to json, i wrote below code, but always return empty, did not figure it out.

you can try below code here: 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)
	}
}

always return {}, i checked this link http://blog.golang.org/json-and-go, did not know why? what's wrong to my code.

答案1

得分: 4

因为json.Marshal位于另一个包中,它只能访问到导出的字段。如果你导出这些字段,它就可以正常工作:http://play.golang.org/p/EMGm5-hs8g

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

英文:

Because json.Marshal is in another package, it only has access to exported fields. If you export the fields it works: http://play.golang.org/p/EMGm5-hs8g

Your other option is to implement the MarshalJson interface yourself (if you don't want to export the fields): http://play.golang.org/p/9gGOBuGbVu

huangapple
  • 本文由 发表于 2014年11月26日 14:49:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/27142959.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定