json.Marshal(struct)返回"{}"

Dou*_*sek 112 json marshalling go

type TestObject struct {
    kind string `json:"kind"`
    id   string `json:"id, omitempty"`
    name  string `json:"name"`
    email string `json:"email"`
}

func TestCreateSingleItemResponse(t *testing.T) {
    testObject := new(TestObject)
    testObject.kind = "TestObject"
    testObject.id = "f73h5jf8"
    testObject.name = "Yuri Gagarin"
    testObject.email = "Yuri.Gagarin@Vostok.com"

    fmt.Println(testObject)

    b, err := json.Marshal(testObject)

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

    fmt.Println(string(b[:]))
}
Run Code Online (Sandbox Code Playgroud)

这是输出:

[ `go test -test.run="^TestCreateSingleItemResponse$"` | done: 2.195666095s ]
    {TestObject f73h5jf8 Yuri Gagarin Yuri.Gagarin@Vostok.com}
    {}
    PASS
Run Code Online (Sandbox Code Playgroud)

为什么JSON基本上是空的?

Cer*_*món 201

您需要通过大写字段名称中的第一个字母来导出 TestObject中的字段.更改kindKind等.

type TestObject struct {
 Kind string `json:"kind"`
 Id   string `json:"id,omitempty"`
 Name  string `json:"name"`
 Email string `json:"email"`
}
Run Code Online (Sandbox Code Playgroud)

encoding/json包和类似的包忽略未导出的字段.

`json:"..."`字段声明后面的字符串是struct标记.此结构中的标记在编组JSON时和从JSON编组时设置结构字段的名称.

playground

  • @user123456 使用“json”字段标签将 JSON 字段名称设置为小写名称(如本答案最后一段所述)。 (2认同)

Sou*_*gat 25

  • 当第一个字母大写时,标识符对您要使用的任何代码段都是公共的.
  • 当第一个字母是小写时,标识符是私有的,只能在声明它的包中访问.

例子

 var aName // private

 var BigBro // public (exported)

 var 123abc // illegal

 func (p *Person) SetEmail(email string) {  // public because SetEmail() function starts with upper case
    p.email = email
 }

 func (p Person) email() string { // private because email() function starts with lower case
    return p.email
 }
Run Code Online (Sandbox Code Playgroud)

  • 很棒的男人,工作完美只会改变第一封信给大写,非常感谢你 (3认同)
  • 确切地说,`在Go中,如果名称以大写字母开头,则会导出名称.将它放在上下文中,请访问[Go Basics Tour](https://tour.golang.org/basics/3) (2认同)

sup*_*rup 5

在 golang

在 struct 中的第一个字母必须大写,例如。电话号码 -> 电话号码

====== 添加细节

首先,我尝试这样编码

type Questions struct {
    id           string
    questionDesc string
    questionID   string
    ans          string
    choices      struct {
        choice1 string
        choice2 string
        choice3 string
        choice4 string
    }
}
Run Code Online (Sandbox Code Playgroud)

golang compile 不是错误并且不显示警告。但响应是空的,因为某事

之后,我搜索谷歌找到了这篇文章

结构类型和结构类型文字 文章然后...我尝试编辑代码。

//Questions map field name like database
type Questions struct {
    ID           string
    QuestionDesc string
    QuestionID   string
    Ans          string
    Choices      struct {
        Choice1 string
        Choice2 string
        Choice3 string
        Choice4 string
    }
}
Run Code Online (Sandbox Code Playgroud)

是工作。

希望得到帮助。