我在go中拥有以下PartnerType
“枚举”结构:
// PartnerType enum
type PartnerType int
const (
// 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 enum
func (t PartnerType) MarshalJSON() ([]byte, error) {
s := t.String()
return json.Marshal(s)
}
// UnmarshalJSON for enum
func (t *PartnerType) UnmarshalJSON(b []byte) error {
*t = PartnerTypeUnknown
return nil
}
// MarshalText implements the text marshaller method
func (t *PartnerType) MarshalText() ([]byte, error) {
return []byte(t.String()), nil
}
// UnmarshalText implements the text unmarshaller method
func (t *PartnerType) UnmarshalText(text []byte) error {
*t = PartnerTypeUnknown
return nil
}
// Partner entity
type Partner struct {
ID string `dynamodbav:"PK,omitempty"`
Foo string `dynamodbav:"SK,omitempty"`
PartnerType PartnerType `dynamodbav:",omitempty,string"`
}
执行dynamodbattribute.MarshalMap()
时,我希望将PartnerType
存储为字符串。 dynamodbav struct标记允许您将int作为字符串(dynamodbav:",omitempty,string"
)存储,但是它没有调用我定义的.String()
或Marshal/Unmarshal
实现。
用另一种方式表示,它将PartnerTypeTest
存储为"1"
而不是"TEST"
。
这怎么办?
答案 0 :(得分:1)
对于dynamodb,您可以为枚举实现marshaler / unmarshaler
尝试以下操作:
// 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
}