json - DynamoDB UnmarshalListOfMaps 在 Go 中创建空值

标签 json amazon-web-services go amazon-dynamodb unmarshalling

我从 json 文件中放入项目,我的代码可以输出扫描结果 json,但尝试使用内置进程将其解码为我的类型只会创建空值/零值。

预期:0,番茄,0.50

实际:0, , 0

项目.json

{
    "id" : {"N" : "0"},
    "description" : {"S": "tomato"},
    "price" : {"N": "0.50"}
}

产品.go

type product struct {
    id          int
    description string
    price       float64
}

我的查询函数:

func listAllProducts() []product {
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-east-1"),
    },
    )
    svc := dynamodb.New(sess)
    productList := []product{}

    input := &dynamodb.ScanInput{
        TableName: aws.String("Products"),
    }
    result, err := svc.Scan(input)
    err = dynamodbattribute.UnmarshalListOfMaps(result.Items, &productList)
    return productList
}

输出代码

productList := listAllProducts()

    for _, p := range productList {
        log.Println(strconv.Itoa(p.id) + ", " + p.description + ", " + strconv.FormatFloat(p.price, 'f', -1, 64))
    }

最佳答案

Marshal documentation说:

All struct fields and with anonymous fields, are marshaled unless the any of the following conditions are meet.

  • the field is not exported

Unmarshal 文档没有提及任何关于非导出字段的内容,但在 Go 中很常见并且预期在解码时也忽略非导出字段(你甚至不能 set non-exported fields毕竟使用 Go 的反射)。

我不知道如何使用 DynamoDB,但如果导出您的字段,您可能会好运:

type product struct {
    Id          int
    Description string
    Price       float64
}

如果您需要使用小写字段名称编码结构,可以使用 dynamodbav 结构标记。

我还建议注意 dynamodbattribute.UnmarshalListOfMaps 返回的错误:

err = dynamodbattribute.UnmarshalListOfMaps(result.Items, &productList)
if err != nil {
    /* Do something with the error here even if you just log it. */
}

对于 svc.Scan(input) 调用以及返回错误的所有其他内容也是如此。

关于json - DynamoDB UnmarshalListOfMaps 在 Go 中创建空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49714414/

相关文章:

c# - 仅当数组为空时 JSON 反序列化才会失败

java - Spring POST 请求不支持的媒体类型 415

python - AWS lambda : cannot import name '_imaging' from 'PIL'

java - AWS 无法验证提供的访问凭证(eclipse)

json - 通过多个编码保留 json.RawMessage

javascript - 在 Javascript 中访问 Json

javascript - 处理响应 - SyntaxError : Unexpected end of input when using mode: 'no-cors'

amazon-web-services - ALB 每 35 秒重复调用一次 AWS Lambda

go - 如何在子目录中加载模板

azure - 在 Azure 存储元数据中使用国际字符?