请帮助我完成以下操作,因为无论json响应的类型如何,条件都会被执行。这是一个返回json的示例公共url,如果响应符合结构,我们只记录标题。不管json响应是什么,代码都会进入条件(err==nil(。json解码器应该检查响应的结构,如果我没有错的话。
我的代码在下完成
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
)
type response struct {
UserID int `json:"userId"`
ID int `json:"id"`
Title string `json:"title"`
Body string `json:"body"`
}
func main() {
resp, err := http.Get("https://jsonplaceholder.typicode.com/posts/1")
if err != nil {
log.Fatalln(err)
}
var actual response
if err = json.NewDecoder(resp.Body).Decode(&actual); err == nil {
fmt.Printf("anotherLink from docker container: %s", actual.Title)
}
默认情况下,忽略没有相应结构字段的对象键。使用DisableUnknownFields可使解码器返回未知密钥的错误。
d := json.NewDecoder(resp.Body)
d.DisallowUnknownFields()
if err = d.Decode(&actual); err == nil {
fmt.Printf("anotherLink from docker container: %s", actual.Title)
}
这种方法的问题在于,结构类型必须包括服务器发送的每个字段。如果服务器将来添加新字段,解码将失败。
如果未设置指定字段,则更好的选择是拒绝响应。
if err = json.NewDecoder(resp.Body).Decode(&actual); err != nil || actual.UserID == "" {
// Handle bad response.
}