如何解组JSON数据定义在良好的格式打印

问题描述 投票:-3回答:1

我不能找出如何解组由API提供的JSON数据且消耗所述数据以指定的格式打印。

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

type postOffice []struct {
    Name    string
    Taluk   string
    Region  string
    Country string
}

func main() {
    data, err := http.Get("http://postalpincode.in/api/pincode/221010")
    if err != nil {
        fmt.Printf("The http request has a error : %s", err)
    } else {
        read, _ := ioutil.ReadAll(data.Body)
        var po postOffice
        err = json.Unmarshal(read, &po)
        if err != nil {
            fmt.Printf("%s", err)
        }
        fmt.Print(po)
    }

}

代码运作良好,直到“读取”进行了评价,但投掷使用json.Unmarshal以下错误“JSON:不能解组对象进型main.post []转到值”

json api go unmarshalling
1个回答
2
投票

您需要创建第二个结构接收整个JSON。

type JSONResponse struct {
    Message    string     `json:"Message"`
    Status     string     `json:"Success"`
    PostOffice postOffice `json:"PostOffice"`
}

这是因为PostOffice是响应的内部的阵列。

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

//this is the new struct
type JSONResponse struct {
    Message    string     `json:"Message"`
    Status     string     `json:"Success"`
    PostOffice postOffice `json:"PostOffice"`
}

type postOffice []struct {
    Name    string
    Taluk   string
    Region  string
    Country string
}

func main() {
    data, err := http.Get("http://postalpincode.in/api/pincode/221010")
    if err != nil {
        fmt.Printf("The http request has a error : %s", err)
    } else {
        read, _ := ioutil.ReadAll(data.Body)
        //change the type of the struct
        var po JSONResponse
        err = json.Unmarshal(read, &po)
        if err != nil {
            fmt.Printf("%s", err)
        }
        fmt.Print(po)
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.