代码之家  ›  专栏  ›  技术社区  ›  John

DynamoDB UnmarshalListOfMaps在Go中创建空值

  •  1
  • John  · 技术社区  · 8 年前

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

    预期值:0,番茄,0.50

    实际值:0,0

    项目json

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

    产品去

    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))
        }
    
    1 回复  |  直到 8 年前
        1
  •  6
  •   mu is too short    7 年前

    这个 Marshal documentation 表示:

    除非满足以下任何条件,否则将封送所有结构字段和匿名字段。

    • 该字段未导出

    这个 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) 调用以及其他返回错误的内容。