执行UnmarshalExtJSON时无效的读取数组请求

时间:2019-05-06 22:49:34

标签: go unmarshalling mongo-go

我正在尝试使用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版本

1 个答案:

答案 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$