简体   繁体   中英

golang json marshalling with embedded struct not working

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

What I get is just the encoding of Bucket. For eg, 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 ?

The location field of AWSS3Bucket is not exported (ie 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"`
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM