Go json.Marshal(struct)返回“{}”。 [英] Go json.Marshal(struct) returns "{}"

查看:120
本文介绍了Go json.Marshal(struct)返回“{}”。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 类型TestObject结构{
kind string`json:kind`
id字符串`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)
$ bb,err:= json.Marshal(testObject)
$ b $ if err!= nil {
fmt.Println(err)
}

fmt.Println(字符串(b [:]))
}



以下是输出:

  [ `go test -test.run =^ TestCreateSingleItemResponse $`|完成:2.195666095s] 
{TestObject f73h5jf8 Yuri Gagarin Yuri.Gagarin@Vostok.com}
{}
PASS

为什么JSON本质上是空的?

解决方案

您需要导出 TestObject中的字段,方法是大写字段名中的第一个字母。将 kind 更改为 Kind 等。



<$ p $ 类型TestObject结构{
类型字符串`json:kind`
Id字符串`json:id,omitempty`
名称字符串`json:名称`
电子邮件字符串`json:email`
}

编码/ json包和类似包忽略未报告的字段。


$ b `json:...`字段声明后面的字符串是结构标签。这个结构中的标签在封送到JSON和从JSON封送时设置结构字段的名称。

org / p / n19J5XhiGILrel =noreferrer> playground


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[:]))
}

Here is the output:

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

Why is the JSON essentially empty?

解决方案

You need to export the fields in TestObject by capitalizing the first letter in the field name. Change kind to Kind and so on.

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.

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.

playground

这篇关于Go json.Marshal(struct)返回“{}”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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