我有一个类型叫做 Period
看起来像这样:
type Period struct {
Year int
Month int
Day int
}
func (period *Period) String() string {
if Day == 0 {
return fmt.Sprintf("%d-%02d", period.Year, period.Month)
}
return fmt.Sprintf("%d-%02d-%02d", period.Year, period.Month, period.Day)
}
func (period *Period) MarshalJSON() ([]byte, error) {
return []byte(period.String()), nil
}
func (period *Period) UnmarshalJSON(raw []byte) error {
parsed, err := ParsePeriod(string(raw))
*period = *parsed
return err
}
我遇到的问题是,如果我有一个带有 *Period
的结构在其中,调用dynamodbattributes.MarshalMap
不会以我想要的方式编码/解码它。例如,type testStruct struct {
Period *Period `json:"period,string"`
}
p := testStruct{Period: &Period{Year: 2020, Month: 7, Day: 31}}
attrs, _ := dynamodbattributes.MarshalMap(&p)
fmt.Printf("Attributes: %v\n", attrs)
将产生:Attributes: map["period"] {
M: {
Year: {
N: "2020"
},
Month: {
N: "7"
},
Day: {
N: "31"
}
}
}
我更喜欢调用生产:Attributes: map["period"] {
S: "2020-07-31"
}
有没有办法在不对值进行硬编码的情况下实现这一点?
最佳答案
我认为 dynamodbattributes.MarshalMap 使用了另一个自定义函数:MarshalDynamoDBAttributeValue
和 UnmarshalDynamoDBAttributeValue
而不是 MarshalJSON
和 UnmarshalJSON
https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/dynamodbattribute/#UnixTime
关于json - 在 Go 中使用客户编码(marshal)函数与 dynamodbattributes.MarshalMap 进行类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63186435/