json - 在 Go 中使用客户编码(marshal)函数与 dynamodbattributes.MarshalMap 进行类型

标签 json go amazon-dynamodb

我有一个类型叫做 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 使用了另一个自定义函数:MarshalDynamoDBAttributeValueUnmarshalDynamoDBAttributeValue而不是 MarshalJSONUnmarshalJSON 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/

相关文章:

database - 如何从 Go 中的多个表构造对象

go - go.mod中的 'incompatible'是什么意思,会不会造成危害?

amazon-web-services - DynamoDB 多个筛选条件,给出错误 - buildTree 错误 : unset parameter: ConditionBuilder

amazon-dynamodb - 如何在 dynamodb 中添加空映射或数据映射?

javascript - 在 PHP 中构建 JSON 并在 <script> 中回显时转义字符

jquery - 按id升序加载图片

javascript - 通过 Ajax/JSON 创建滑动的下一个/上一个内容

带有 Go 插件的 Dockerfile

java - dynamoDB mapper scan() 错误 : java. lang.NullPointerException: null

php - 从 MySQL 获取数据并使用 JSON 在 ListView 中显示