gpt4 book ai didi

json - 将 mongo 条目解析为结构

转载 作者:IT王子 更新时间:2023-10-29 01:06:29 26 4
gpt4 key购买 nike

我有具有以下模式的 mongo 数据库

{ 
"_id" : ObjectId("55c8526d8c16598efb5ee1e6"),
"guid" : "72811d52b48379e72c8fdd11aa09cb8b",
"blkid" : 1,
"vblkid" : 0,
"spltid" : 0,
"cmpr" : false,
"encr" : false,
"chksum" : "",
"dup" : false,
"cid" : 1,
"off" : 524508,
"len" : 524408,
"incr" : 0,
"fBackupID" : 0,
"vid" : 0,
"plugInType" : 0,
"blkType" : 0,
"alen" : 0
}

我正在尝试将它们解析为具有以下结构的结构:

type VhfsBlockMD struct {
GUID string `json:"guid"`
BlkID int `bson:",minsize" json:"blkid"`
VBlkID int `bson:",minsize" json:"vblkid"`
SpltID int `bson:",minsize" json:"spltid"`
Cmpr bool `json:"cmpr" `
Encr bool `json:"encr"`
Blksum string `bson:"blksum,omitempty" json:"blksum,omitempty"`
Chksum string `json:"chksum"`
Dup bool `json:"dup"`
Cid int `bson:",minsize" json:"cid"`
SplitLen int `bson:",minsize" json:"len"`
Off int64 `bson:",minsize" json:"off"`
Incr int `bson:",minsize" json:"incr"`
CDup bool `bson:"cdup,omitempty" json:"cdup,omitempty"`
FBackupID int `bson:"fBackupID" json:"fBackupID"`
Vid int `bson:"vid" json:"vid"`
PlugInType int `bson:"plugInType" json:"plugInType"`
BlkType int `bson:"blkType" json:"blkType"`
Alen int `bson:"alen" json:"alen"`
IsValid int `bson:"-" json:"-"`
Len uint64 `bson:"-" json:"-"`
}

我正在使用 mgo 驱动程序。

现在的问题是,在解析后我无法正确解析的唯一属性是“len”(go struct 中的 SplitLen)。

len 定义为

SplitLen int `bson:",minsize" json:"len"`

我相信它与标签有关。另外我想提一下,同样的结构被用来将值插入到 mongodb 中。

如有任何帮助,我们将不胜感激。

最佳答案

如果数据元素在其他表示(例如 json 文本或数据库)中以与结构字段名称不同的名称出现,您必须在字段标记中告知要与结构字段匹配的名称。

您告诉 json 包获取/设置 json 值 "len" 到字段 SplitLen 中,该字段通过包含此名称而不同在其标签中:json:"len"

但是您还没有告诉 mongo 驱动程序也使用这个字段,它很可能在您的 mongodb 中命名为 "Len"(或 "len")。您明确排除了可以按名称“自动匹配”的字段:

Len uint64 `bson:"-" json:"-"`

正如 Ainar-G 所建议的,您可以通过将 “len” 添加到 bson 标记值来指定该字段,这将强制 mgo 驱动程序也使用 SplitLen 字段:

SplitLen int `bson:"len,minsize" json:"len"`

现在我看不到 Len 字段有任何用途,您应该将其删除以避免混淆,或者使用 Len 名称而不是 SplitLen :

Len int `bson:"len,minsize" json:"len"`

关于json - 将 mongo 条目解析为结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31915888/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com