json.Marshal(struct) 返回“{}”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26327391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:34:24  来源:igfitidea点击:

json.Marshal(struct) returns "{}"

jsongomarshalling

提问by Doug Knesek

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 = "[email protected]"

    fmt.Println(testObject)

    b, err := json.Marshal(testObject)

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

    fmt.Println(string(b[:]))
}

Here is the output:

这是输出:

[ `go test -test.run="^TestCreateSingleItemResponse$"` | done: 2.195666095s ]
    {TestObject f73h5jf8 Yuri Gagarin [email protected]}
    {}
    PASS

Why is the JSON essentially empty?

为什么 JSON 本质上是空的?

回答by Cerise Limón

You need to exportthe fields in TestObject by capitalizing the first letter in the field name. Change kindto Kindand so on.

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

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

The encoding/json package and similar packages ignore unexported fields.

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

The `json:"..."`strings that follow the field declarations are struct tags. The tags in this struct set the names of the struct's fields when marshaling to and from JSON.

`json:"..."`字段声明后面的字符串是struct tags。在与 JSON 之间进行封送处理时,此结构中的标签设置结构字段的名称。

playground

playground

回答by Sourabh Bhagat

  • When the first letter is capitalised, the identifier is public to any piece of code that you want to use.
  • When the first letter is lowercase, the identifier is private and could only be accessed within the package it was declared.
  • 当第一个字母大写时,标识符对您要使用的任何代码段都是公开的。
  • 当第一个字母是小写时,标识符是私有的,只能在它声明的包内访问。

Examples

例子

 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
 }

回答by superup

In golang

在 golang

in struct first letter must uppercase ex. phonenumber -> PhoneNumber

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

======= Add detail

======== 添加细节

First, I'm try coding like this

首先,我尝试这样编码

type Questions struct {
    id           string
    questionDesc string
    questionID   string
    ans          string
    choices      struct {
        choice1 string
        choice2 string
        choice3 string
        choice4 string
    }
}

golang compile is not error and not show warning. But response is empty because something

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

After that, I search google found this article

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

Struct Types and Struct Type Literals Articlethen... I try edit code.

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

//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
    }
}

Is work.

是工作。

Hope for help.

希望得到帮助。