猿问

Golang 解组 json 列表

我一直在努力解析一个基本的数组响应。


我的输入 JSON 有一个结构类型一致的列表。


[

{

  "amount":"6.40000000",

  "date":"1439165701",

  "price":"350.26",

  "tid":104159

},

{

  "amount":"0.10025000",

  "date":"1439162764",

  "price":"351.03",

  "tid":104150

}

]

我的结构有一个嵌套的数组结构。


type TransactionResponse struct {

    Transaction []Transaction

}

type Transaction struct {

    Amount string `json:"amount"`

    Date   string `json:"date"`

    Price  string `json:"price"`

    tid    uint   `json:"tid"`

}

解析json的函数:


func main() {

    var transactions TransactionResponse


    body, err := http.Get(url)

    err = json.Unmarshal(body, &transactions)

}

我哪里错了?


largeQ
浏览 159回答 2
2回答

繁花如伊

解码为交易切片:body, err := http.Get(url)var transactions []Transactionerr = json.Unmarshal(body, &transactions)此外,导出所有字段:type Transaction struct {  Amount string `json:"amount"`  Date   string `json:"date"`  Price  string `json:"price"`  Tid    uint   `json:"tid"`}

肥皂起泡泡

所以是的,花了一段时间......TransactionResponse 不是结构类型。如果我将其设置为 Transaction 数组,它就可以正常工作。package mainimport "fmt"import "encoding/json"var body = `[{"amount":"6.40000000","date":"1439165701","price":"350.26","tid":104159},{"amount":"0.10025000","date":"1439162764","price":"351.03","tid":104150}]`type TransactionResponse []Transactiontype Transaction struct {Amount string `json:"amount"`Date   string `json:"date"`Price  string `json:"price"`tid    uint   `json:"tid"`}func main() {var transactions TransactionResponseerr := json.Unmarshal([]byte(body), &transactions)if err != nil {    panic(err)}fmt.Println(transactions)}
随时随地看视频慕课网APP

相关分类

Go
我要回答