duangan1945 2015-03-13 20:56
浏览 109
已采纳

使用golang的encoding / json读取嵌套的json数据

I can't get the correct definition for my structs to capture the nested json data saved in a variable. My code snippet is as below:

package main

import "fmt"
import "encoding/json"

type Data struct {
    P string `json:"ports"`
    Ports struct {
         Portnums []int
    }
    Protocols []string `json:"protocols"`
}

func main() {
        y := `{
                "ports": {
            "udp": [
                1, 
                30
            ], 
            "tcp": [
                100, 
                1023
            ]
            }, 
            "protocols": [
            "tcp", 
            "udp"
            ]
    }`
    var data Data
    e := json.Unmarshal([]byte(y), &data)
    if e == nil {
        fmt.Println(data)
    } else {
        fmt.Println("Failed:", e)
    }

}

$ go run foo.go 
Failed: json: cannot unmarshal object into Go value of type string
  • 写回答

1条回答 默认 最新

  • doudansui6650 2015-03-13 21:18
    关注

    This works for me (see comment to your question above) <kbd>GoPlay</kbd>

    type Data struct {
        Ports struct {
            Tcp []float64 `json:"tcp"`
            Udp []float64 `json:"udp"`
        } `json:"ports"`
        Protocols []string `json:"protocols"`
    }
    
    func main() {
        y := `{
                    "ports": {
                "udp": [
                    1, 
                    30
                ], 
                "tcp": [
                    100, 
                    1023
                ]
                }, 
                "protocols": [
                "tcp", 
                "udp"
                ]
        }`
        d := Data{}
        err := json.Unmarshal([]byte(y), &d)
        if err != nil {
            fmt.Println("Error:", err.Error())
        } else {
            fmt.Printf("%#+v", d)
        }
    
    }
    

    OUTPUT

    main.Data{
        Ports:struct { 
            Tcp []float64 "json:\"tcp\"";
            Udp []float64 "json:\"udp\"" 
        }{
            Tcp:[]float64{100, 1023},
            Udp:[]float64{1, 30}
        },
        Protocols:[]string{"tcp", "udp"}
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构