我在 go 中有以下PartnerType“enum”结构:// PartnerType enumtype PartnerType intconst ( // PartnerTypeUnknown should never happen PartnerTypeUnknown PartnerType = iota // PartnerTypeTest test PartnerTypeTest)func (t PartnerType) String() string { names := [...]string{ "UNKNOWN", "TEST"} if t < PartnerTypeUnknown || t > PartnerTypeTest { return names[0] } return names[t]}// MarshalJSON for enumfunc (t PartnerType) MarshalJSON() ([]byte, error) { s := t.String() return json.Marshal(s)}// UnmarshalJSON for enumfunc (t *PartnerType) UnmarshalJSON(b []byte) error { *t = PartnerTypeUnknown return nil}// MarshalText implements the text marshaller methodfunc (t *PartnerType) MarshalText() ([]byte, error) { return []byte(t.String()), nil}// UnmarshalText implements the text unmarshaller methodfunc (t *PartnerType) UnmarshalText(text []byte) error { *t = PartnerTypeUnknown return nil}// Partner entitytype Partner struct { ID string `dynamodbav:"PK,omitempty"` Foo string `dynamodbav:"SK,omitempty"` PartnerType PartnerType `dynamodbav:",omitempty,string"`}在执行 a 时,dynamodbattribute.MarshalMap()我希望PartnerType将 my 存储为字符串。dynamodbav结构标记允许您将 int 存储为字符串 ( ) ,dynamodbav:",omitempty,string"但它不会调用我定义的.String()或Marshal/Unmarshal实现。换句话说,它存储PartnerTypeTest为"1"not "TEST"。如何才能做到这一点?
1 回答
四季花海
TA贡献1811条经验 获得超5个赞
对于 dynamodb,您可以为枚举实现编组器/解组器
请尝试以下操作:
// MarshalDynamoDBAttributeValue for ddb
func (t PartnerType) MarshalDynamoDBAttributeValue(av *dynamodb.AttributeValue) error {
s := t.String()
av.S = &s
return nil
}
// UnmarshalDynamoDBAttributeValue implements the Unmarshaler interface
func (t *PartnerType) UnmarshalDynamoDBAttributeValue(av *dynamodb.AttributeValue) error {
// val := aws.StringValue(av.S)
*t = PartnerTypeUnknown
return nil
}
- 1 回答
- 0 关注
- 144 浏览
添加回答
举报
0/150
提交
取消