【发布时间】:2021-05-05 08:18:08
【问题描述】:
如何使用 Golang cloud.google.com 库将 EmbeddedEntity 写入数据存储区?
我在一家公司工作,我们正在从 GCP Java 迁移到 Golang。 Java Core 要求将 EmbeddedEntitys 写入 Datastore,以便 Core 获取和读取有关用户的某些信息。
我们正在迁移到 Golang,并要求使用 Golang 编写 EmbeddedEntity。我尝试将Struct 编组为JSON,并直接写出来。但是,它仍然保留为String 类型。在 Java Core 中更改生产代码目前对我们来说不是一个可行的选择。
// VBalEmbeddedEntity is a Struct representation of a JSON entity
type VBalEmbeddedEntity struct {
Properties Properties `json:"properties"`
}
type Properties struct {
VT1_1 IntegerValue `json:"VT1_1"`
}
type IntegerValue struct {
IntegerValue string `json:"integerValue"`
}
// Create EmbeddedEntity
bytes, err := json.Marshal(VBalEmbeddedEntity{
Properties: Properties{
VT1_1: IntegerValue{
IntegerValue: strconv.Itoa(int(record.Amount)),
},
},
})
if err != nil {
return 0, 0, err
}
// Generate Data using record
vbal := string(bytes)
f4Key := datastore.IncompleteKey("MyKind", nil)
f4E := F1_4{VBal: vbal}
// Datastore Put
d.DB.Put(ctx, f4Key, &f4E)
【问题讨论】:
-
IntegerValue.IntegerValue是字符串类型。考虑在IntegerValue int...上将其更改为 int,然后在创建时将其更改为:IntegerValue: int(record.Amount)) -
我会试一试,但 JSON 数据存储区需要字符串中的数字。我认为这不是问题。
-
目前尚不清楚您为什么要尝试将 VBalEmbeddedEntity 编组为某种格式,而不是让 Datastore 序列化内部属性,例如 pkg.go.dev/cloud.google.com/go/… 。也许一个工作序列化版本的例子将有助于理解这个问题。
-
@JimMorrison 疯子!完美解决了我的问题!我现在把答案写出来。还没有人问过 Golang 中的 EmbeddedEntitys :) Datastore 中的 JSON 和 Type 与 GCP Java 编写的完全相同。
标签: go google-app-engine google-cloud-platform cloud google-cloud-datastore