dongmei2351 2016-08-02 09:10
浏览 600
已采纳

在Golang中使用json.Decoder解码顶级JSON数组

Is it possible to decode top level JSON array with json.Decoder?

Or reading entire JSON and json.Unmarshall is the only way in this case?

I have read the accepted answer in this question and cannot figure out how to use it with top level JSON array

  • 写回答

2条回答 默认 最新

  • duanliangman5398 2016-08-02 10:04
    关注

    You use json.Decoder in same way as any other json. Only difference is that instead of decoding into a struct, json need to be decoded in array of struct. This is a very simple example. Go Playground

    package main
    
    import (
        "bytes"
        "encoding/json"
        "fmt"
    )
    
    type Result struct {
        Name         string `json:"Name"`
        Age          int    `json:"Age`
        OriginalName string `json:"Original_Name"`
    }
    
    func main() {
        jsonString := `[{"Name":"Jame","Age":6,"Original_Name":"Jameson"}]`
        result := make([]Result, 0)
        decoder := json.NewDecoder(bytes.NewBufferString(jsonString))
        err := decoder.Decode(&result)
        if err != nil {
            panic(err)
        }
        fmt.Println(result)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于大棚监测的pcb板设计
  • ¥20 sim800c模块 at指令及平台
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计