douhuang5331 2018-04-15 21:29
浏览 65

带有嵌入式结构的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条回答

  • drba1172 2018-04-15 22:03
    关注

    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"`
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!