我的结构不是编组成json [英] My structures are not marshalling into json

查看:102
本文介绍了我的结构不是编组成json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Mac OS X 10.8.2上使用Go 1.0.3,并且正在试验 json 包,试图将一个结构编组为json,但是我继续获得一个空的 {} json对象。


$ b $ < err 值是零,所以根据 json.Marshal 函数没有任何问题,并且结构是正确的。为什么会发生这种情况?

  package main 

import(
encoding / json
fmt


类型地址struct {
街字符串
扩展字符串
城市字符串
状态字符串
zip string


类型名称struct {
第一个字符串
中间字符串
最后一个字符串
}

类型Person结构{
名称
年龄int
地址地址
手机字符串
}

func main(){
myname:= Name {Alfred,H,Eigenface}
myaddr:=地址{42 Place Rd,Unit 2i,Placeton,ST,00921 }
me:= Person {myname,24,myaddr,000 555-0001}
$ bb,err:= json.Marshal(me)

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

fmt.Println(string(b))// err为零,但b为空,为什么?
fmt.Println(\ n)
fmt.Println(me)//我是预期的,充满数据
}


解决方案

您必须制作您想要公开的字段。
像这样:

 类型地址struct {
街字符串
扩展字符串
城市字符串
州字符串
Zip字符串
}

err nil ,因为所有导出的字段,在这种情况下都没有,被正确编组。



工作示例: http://play.golang.org/p/ 0Q8TIvZwuj



查看文档 http://godoc.org/encoding/json/#Marshal


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("\n")
  fmt.Println(me)           // me is as expected, full of data
}

解决方案

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: http://play.golang.org/p/0Q8TIvZwuj

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

这篇关于我的结构不是编组成json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆