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

报告相同问题?

悬赏问题

  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM