我正在尝试使用UnmarshalExtJSON
中的go.mongodb.org/mongo-driver/bson
将扩展JSON解组为结构体
给我一个错误:invalid request to read array
如何将这些数据解组到我的结构中?
MVCE:
package main
import (
"fmt"
"go.mongodb.org/mongo-driver/bson"
)
func main() {
var json = "{\"data\":{\"streamInformation\":{\"codecs\":[\"avc1.640028\"]}}}"
var workflow Workflow
e := bson.UnmarshalExtJSON([]byte(json), false, &workflow)
if e != nil {
fmt.Println("err is ", e)
// should print "err is invalid request to read array"
return
}
fmt.Println(workflow)
}
type Workflow struct {
Data WorkflowData `json:"data,omitempty"`
}
type WorkflowData struct {
StreamInformation StreamInformation `json:"streamInformation,omitempty"`
}
type StreamInformation struct {
Codecs []string `json:"codecs,omitempty"`
}
我正在使用1.12.4 Windows / amd64版本
答案 0 :(得分:1)
您正在使用bson
包进行解组,但是您正在使用json
结构字段标记。将它们更改为bson
结构字段标记,它应该对您有用:
package main
import (
"fmt"
"go.mongodb.org/mongo-driver/bson"
)
func main() {
var json = "{\"data\":{\"streamInformation\":{\"codecs\":[\"avc1.640028\"]}}}"
var workflow Workflow
e := bson.UnmarshalExtJSON([]byte(json), false, &workflow)
if e != nil {
fmt.Println("err is ", e)
return
}
fmt.Println(workflow)
}
type Workflow struct {
Data WorkflowData `bson:"data,omitempty"`
}
type WorkflowData struct {
StreamInformation StreamInformation `bson:"streamInformation,omitempty"`
}
type StreamInformation struct {
Codecs []string `bson:"codecs,omitempty"`
}
输出:
paul@mac:bson$ ./bson
{{{[avc1.640028]}}}
paul@mac:bson$