dongyin2643 2019-05-06 22:49
浏览 120
已采纳

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

I'm trying to unmarshal extended JSON into a struct using UnmarshalExtJSON from go.mongodb.org/mongo-driver/bson

It's giving me an error: invalid request to read array

How can I unmarshal this data into my struct?

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"`
}

I'm using go version 1.12.4 windows/amd64

  • 写回答

1条回答 默认 最新

  • dstt1818 2019-05-06 23:28
    关注

    You're unmarshalling using the bson package, but you're using json struct field tags. Change them to bson struct field tags and it should work for you:

    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"`
    }
    

    with output:

    paul@mac:bson$ ./bson
    {{{[avc1.640028]}}}
    paul@mac:bson$ 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题