go 的json解析问题

Greg_han 2014-07-30 06:09:11
type Message struct {
Name string
Body string
Time int64
Parents *ParentS
}

type ParentS struct{
father string
mother string
}

pp := &ParentS{"Zhang","li"}


m := Message{"Alice", "Hello", 1294706395881547000,pp}

fmt.Println("father is",m.Parents.father)

x, err := json.Marshal(m)
if err != nil {
fmt.Printf("error is %v\n", err)
} else {
fmt.Printf("解析=%s",x)
}


///////////////////////////////输出怎样出现了 空{}???如下:
father is Zhang
解析={"Name":"Alice","Body":"Hello","Time":1294706395881547000,"Parents":{}}
...全文
120 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
svenwang 2014-07-30
  • 打赏
  • 举报
回复
如果你要导出struct的成员,成员名的首字母要大写。 所以

type ParentS struct {
	father string
	mother string
}
要改成:

type ParentS struct {
	Father string
	Mother string
}
最终代码如下:

package main

import (
	"encoding/json"
	"fmt"
)

type Message struct {
	Name    string
	Body    string
	Time    int64
	Parents *ParentS
}

type ParentS struct {
	Father string
	Mother string
}

func main() {
	pp := &ParentS{"Zhang", "li"}
	m := Message{"Alice", "Hello", 1294706395881547000, pp}
	fmt.Println("father is", m.Parents.Father)
	x, err := json.Marshal(m)
	if err != nil {
		fmt.Printf("error is %v\n", err)
	} else {
		fmt.Printf("解析=%s", x)
	}
}
输出信息:

father is Zhang
解析={"Name":"Alice","Body":"Hello","Time":1294706395881547000,"Parents":{"Father":"Zhang","Mother":"li"}}

2,348

社区成员

发帖
与我相关
我的任务
社区描述
go语言学习与交流版
社区管理员
  • go语言社区
  • 俺叫西西弗斯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧