亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

json:無法將數組解組為結構類型的 Go 值

json:無法將數組解組為結構類型的 Go 值

Go
智慧大石 2022-05-05 16:01:15
我正在構建一個從倫敦地鐵 API 讀取信息的應用程序。我正在努力將 GET 請求解析為可讀的內容,并且用戶可以在其中訪問特定的行信息。這是我當前的代碼,我正在使用一個結構來存儲解組后來自 GET 請求的響應。// struct for decoding into a structure    var tubeStatuses struct {        object []struct {            typeDef      []string `json:"$type"`            idName       string   `json:"id"`            name         string   `json:"name"`            modeName     string   `json:"modeName"`            disruptions  string   `json:"disruption"`            created      string   `json:"created"`            modified     string   `json:"modified"`            statusObject []struct {                zeroObject []struct {                    typeDef        string `json:"$type"`                    id             int    `json:"id"`                    statusSeverity int    `json:"statusSeverity"`                    statusDesc     string `json:"statusSeverityDescription"`                    created        string `json:"created"`                    validity       string `json:"validityPeriods"`                }            }            route         string `json:"routeSections"`            serviceObject []struct {                zeroObject []struct {                    typeDef string `json:"$type"`                    name    string `json:"name"`                    uri     string `json:"uri"`                }            }            crowdingObject []struct {                typeDef string `json:"$type"`            }        }    }    fmt.Println("Now retrieving Underground line status, please wait...")    // two variables (response and error) which stores the response from e GET request    getRequest, err := http.Get("https://api.tfl.gov.uk/line/mode/tube/status")    fmt.Println("The status code is", getRequest.StatusCode, http.StatusText(getRequest.StatusCode))    if err != nil {        fmt.Println("Error!")        fmt.Println(err)    }數組解組為可讀的內容?
查看完整描述

2 回答

?
www說

TA貢獻1775條經驗 獲得超8個贊

以下是您的代碼的工作版本。但是,您需要解決多個問題。

  1. 正如本線程其他地方所提到的,您應該將 TubeStatuses(注意大寫)設置為一個類型和一個數組。字段名稱也應大寫,以便導出。

  2. 您沒有考慮所有輸出,并且在某些情況下類型錯誤。例如,您缺少一個名為“Disruption”的對象。我已經在我的示例中添加了它。“擁擠”聲明的類型錯誤。此外,“route”又名“routeSections”不是字符串。這是另一個數組,可能是對象,但 API 沒有輸出讓我確定 routeSections 實際包含的內容。因此,作為一種解決方法,我將其聲明為“json.RawMessage”的一種類型,以允許將其解組為字節片。有關更多詳細信息,請參見:https ://golang.org/pkg/encoding/json/#RawMessage

  3. 你不能使用json: "$type"`. 具體來說,不允許使用美元符號。

package main


import (

    "encoding/json"

    "fmt"

    "io/ioutil"

    "net/http"

)


type TubeStatuses struct {

    TypeDef      []string `json:"type"`

    IDName       string   `json:"id"`

    Name         string   `json:"name"`

    ModeName     string   `json:"modeName"`

    Disruptions  string   `json:"disruption"`

    Created      string   `json:"created"`

    Modified     string   `json:"modified"`

    LineStatuses []struct {

        Status []struct {

            TypeDef                   string `json:"type"`

            ID                        int    `json:"id"`

            StatusSeverity            int    `json:"statusSeverity"`

            StatusSeverityDescription string `json:"statusSeverityDescription"`

            Created                   string `json:"created"`

            ValidityPeriods           []struct {

                Period struct {

                    TypeDef  string `json: "type"`

                    FromDate string `json: "fromDate"`

                    ToDate   string `json: "toDate"`

                    IsNow    bool   `json: "isNow"`

                }

            }

            Disruption struct {

                TypeDef             string   `json: "type"`

                Category            string   `json: "category"`

                CategoryDescription string   `json: "categoryDescription"`

                Description         string   `json: "description"`

                AdditionalInfo      string   `json: "additionalInfo"`

                Created             string   `json: "created"`

                AffectedRoutes      []string `json: "affectedRoutes"`

                AffectedStops       []string `json: "affectedStops"`

                ClosureText         string   `json: closureText"`

            }

        }

    }

    RouteSections json.RawMessage `json: "routeSections"`

    ServiceTypes  []struct {

        Service []struct {

            TypeDef string `json:"type"`

            Name    string `json:"name"`

            URI     string `json:"uri"`

        }

    }

    Crowding struct {

        TypeDef string `json:"type"`

    }

}


func main() {

    fmt.Println("Now retrieving Underground line status, please wait...")


    // two variables (response and error) which stores the response from e GET request

    getRequest, err := http.Get("https://api.tfl.gov.uk/line/mode/tube/status")

    if err != nil {

        fmt.Println("Error!")

        fmt.Println(err)

    }


    fmt.Println("The status code is", getRequest.StatusCode, http.StatusText(getRequest.StatusCode))


    //close - this will be done at the end of the function

    // it's important to close the connection - we don't want the connection to leak

    defer getRequest.Body.Close()


    // read the body of the GET request

    rawData, err := ioutil.ReadAll(getRequest.Body)


    if err != nil {

        fmt.Println("Error!")

        fmt.Println(err)

    }

    ts := []TubeStatuses{}


    jsonErr := json.Unmarshal(rawData, &ts)


    if jsonErr != nil {

        fmt.Println(jsonErr)

    }


    //test

    fmt.Println(ts[0].Name)


    fmt.Println("Welcome to the TfL Underground checker!\nPlease enter a number for the line you want to check!\n0 - Bakerloo\n1 - central\n2 - circle\n3 - district\n4 - hammersmith & City\n5 - jubilee\n6 - metropolitan\n7 - northern\n8 - piccadilly\n9 - victoria\n10 - waterloo & city")

}

輸出...

http://img1.sycdn.imooc.com//627384770001dd9504110297.jpg

查看完整回答
反對 回復 2022-05-05
?
心有法竹

TA貢獻1866條經驗 獲得超5個贊

您需要該結構的數組:

var tubeStatuses []struct  {...}

此外,您的結構成員名稱不會被導出,因此即使在您執行此操作后它們也不會被解組。大寫名稱。

您的結構很大,因此請考慮將其設為類型。


查看完整回答
反對 回復 2022-05-05
  • 2 回答
  • 0 關注
  • 188 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號