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

Omp*_*ash 1 json marshalling go

我正在尝试扩展 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)
}
Run Code Online (Sandbox Code Playgroud)

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

{"CreationDate":"2016-10-17T22:33:14Z","Name":"test-bucket"}
Run Code Online (Sandbox Code Playgroud)

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

mu *_*ort 7

所述location的场AWSS3Bucket不会导出(即,它不以大写字母开头),所以json使用反射包不能找到它。如果导出字段:

type AWSS3Bucket struct {
    s3.Bucket
    Location string
}
Run Code Online (Sandbox Code Playgroud)

然后它会出现在jsonString. 如果您希望它显示"location":...在 JSON 中,则将其标记为:

type AWSS3Bucket struct {
    s3.Bucket
    Location string `json:"location"`
}
Run Code Online (Sandbox Code Playgroud)