json - 带有嵌入式结构的golang json编码不起作用

标签 json go marshalling

我正在尝试扩展 AWS S3 Bucket 类型以包含附加格式并将其编码为 JSON,但编码不会选择附加字段

这是我的

// AWS has this struct already
type Bucket struct {
    // Date the bucket was created.
    CreationDate *time.Time `type:"timestamp" 
    timestampFormat:"iso8601"`

    // The name of the bucket.
    Name *string `type:"string"`
    // contains filtered or unexported fields
}

// Extended struct
type AWSS3Bucket struct {
    s3.Bucket
    location     string
}

somefunc()
{
    var region string = "us-west-1"
    aws_s3_bucket := AWSS3Bucket{Bucket:*bucket, location:region}
    jsonString, err := json.Marshal(&aws_s3_bucket)
    fmt.Printf("%s\n", jsonString)
}

我得到的只是Bucket的编码。例如,我上面的输出总是这样,没有包含区域

{"CreationDate":"2016-10-17T22:33:14Z","Name":"test-bucket"}

知道为什么该区域没有被编码到 json 缓冲区中吗?

最佳答案

AWSS3Bucketlocation 字段未导出(即它不是以大写字母开头),因此 json 包不能使用反射找到它。如果导出字段:

type AWSS3Bucket struct {
    s3.Bucket
    Location string
}

然后它将显示在 jsonString 中。如果您希望它在 JSON 中显示为 "location":... 然后将其标记为:

type AWSS3Bucket struct {
    s3.Bucket
    Location string `json:"location"`
}

关于json - 带有嵌入式结构的golang json编码不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49846968/

相关文章:

c# - 从 C++ native 插件更新 Vector3 数组

php - 如何从我的网站获取计算机上文件的内容?

ruby-on-rails - Rails 事件资源 : how to send post parameters in the request body and not as query strings?

javascript - JSON 对象被视为字符串

go - 特定错误处理的不明确行为

json - Go JSON命名策略

json - 您如何编码 sql.NullString 以便输出被展平以仅给出 go 中的值?

c# - 如何在c#中访问数据json.net数组

go - 使用golang使用云触发功能在firebase中进行项目间文件传输

docker - docker 容器内文件的 Golang 路径