douya2982 2013-03-16 08:58
浏览 36
已采纳

我的结构没有编组到json中[重复]

This question already has an answer here:

I am using Go 1.0.3 on Mac OS X 10.8.2, and I am experimenting with the json package, trying to marshal a struct to json, but I keep getting an empty {} json object.

The err value is nil, so nothing is wrong according to the json.Marshal function, and the struct is correct. Why is this happening?

package main

import (
  "encoding/json"
  "fmt"
)

type Address struct {
  street string
  extended string
  city string
  state string
  zip string
}

type Name struct {
  first string
  middle string
  last string
}

type Person struct {
  name Name
  age int
  address Address
  phone string
}

func main() {
  myname := Name{"Alfred", "H", "Eigenface"}
  myaddr := Address{"42 Place Rd", "Unit 2i", "Placeton", "ST", "00921"}
  me := Person{myname, 24, myaddr, "000 555-0001"}

  b, err := json.Marshal(me)

  if err != nil {
    fmt.Println(err)
  }

  fmt.Println(string(b))    // err is nil, but b is empty, why?
  fmt.Println("
")
  fmt.Println(me)           // me is as expected, full of data
}
</div>

展开全部

  • 写回答

3条回答 默认 最新

  • douyuan9512 2013-03-16 08:59
    关注

    You have to make the fields that you want to marshal public. Like this:

    type Address struct {
      Street string
      Extended string
      City string
      State string
      Zip string
    }
    

    err is nil because all the exported fields, in this case there are none, were marshalled correctly.

    Working example: https://play.golang.org/p/9NH9Bog8_C6

    Check out the docs http://godoc.org/encoding/json/#Marshal

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部