0

我正在尝试使用UnmarshalExtJSONfrom将扩展 JSON 解组为结构go.mongodb.org/mongo-driver/bson

它给了我一个错误: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"`
}

我正在使用 go 版本 1.12.4 windows/amd64

4

1 回答 1

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$ 
于 2019-05-06T23:28:21.057 回答