Golang DynamoDB UnmarshalListOfMaps 返回空数组

d_t*_*heg 2 go amazon-web-services nosql amazon-dynamodb

我有一个 DynamoDB 产品表(id (int)、active (bool)、name (string)、price (int)),当我检索并尝试解组该列表时,它返回空。

[{},{}]
Run Code Online (Sandbox Code Playgroud)

结构:

type Product struct {
id     int
active bool
name   string
price  int }
Run Code Online (Sandbox Code Playgroud)

解组的代码在这里:

    params := &dynamodb.ScanInput{
    TableName: aws.String("Products"),
}
result, err := service.Scan(params)
if err != nil {
    fmt.Errorf("failed to make Query API call, %v", err)
}

var products = []Product{}

var error = dynamodbattribute.UnmarshalListOfMaps(result.Items, &products)
Run Code Online (Sandbox Code Playgroud)

我在这里做错了什么?

Dmi*_*ski 5

只有公共字段才能被解组。

使用大写字母将结构字段公开,并使用json属性将它们映射到数据值:

type Product struct {
    ID     int    `json:"id"`
    Active bool   `json:"active"`
    Name   string `json:"name"`
    Price  int    `json:"price"`
}
Run Code Online (Sandbox Code Playgroud)

2021 年 10 月更新:

AWS 开发工具包 v1 使用json属性进行 DynamoDB 序列化。新版本aws-sdk-go-v2包含重大更改,并从jsontodynamodbav属性移至单独的 JSON 和 DynamoDB 名称。

对于 V2 结构应如下所示:

type Product struct {
    ID     int    `dynamodbav:"id"`
    Active bool   `dynamodbav:"active"`
    Name   string `dynamodbav:"name"`
    Price  int    `dynamodbav:"price"`
}
Run Code Online (Sandbox Code Playgroud)

文档:https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/dynamodbattribute/#Marshal