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

I'm trying to extend the AWS S3 Bucket type to include an additional format and marshal it as JSON, but the marshalling won't pick up the additional field

This is what I have

// 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
", jsonString)
}

What I get is just the encoding of Bucket. For e.g., my output from above is always like this without the region included

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

Any ideas why the region is not being marshalled into the json buffer ?

1个回答



AWSS3Bucket </ code>的 location </ code>字段未导出(即不导出) 以大写字母开头),因此 json </ code>包无法使用反射找到它。 如果您导出字段:</ p>

 键入AWSS3Bucket结构{
s3.Bucket
位置字符串
}
</ code> </ pre>

然后它将显示在 jsonString </ code>中。 如果您希望它在JSON中显示为“ location”:... </ code>,则将其标记为:</ p>

  type AWSS3Bucket struct {\  n s3.Bucket 
位置字符串json:“ location”
}
</ code> </ pre>
</ div>

展开原文

原文

The location field of AWSS3Bucket is not exported (i.e. it doesn't begin with an upper case letter) so the json package cannot find it using reflection. If you export the field:

type AWSS3Bucket struct {
    s3.Bucket
    Location string
}

then it will show up in jsonString. If you want it to show up as "location":... in the JSON then tag it as such:

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

dsh1102
dsh1102 卫生署! 非常感谢,做到了。
2 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐