英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论