json - 如何解组 json 数据以明确定义的格式打印
问题描述
我不知道如何解组 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: cannot unmarshal object into Go value of type main.post[]”时抛出以下错误
解决方案
您需要创建第二个结构来接收整个 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)
}
}
推荐阅读
- java - Android:如何使用 **Volley** 在导航视图中隐藏登录和注册选项并启用注销选项
- java - Java中的字符串列表
- python - Python S2 库中的多边形支持
- java - Eclipse 大小的 Maven 插件
- asp.net-mvc - ASP.NET MVC - 自定义身份验证不起作用
- variables - TFS/VSTS,在一个变量中引用一个变量
- java - 这是制作继承对象的唯一方法吗?
- mysql - 添加外键约束失败
- api - Lua API 卸载 luaL_loadfile
- python-3.x - 如何从另一个 Python 3 脚本中获取变量?