Json解码始终执行,无论结构如何。

huangapple go评论90阅读模式
英文:

Json decode always executing irrespective of the structure

问题

请帮我翻译以下内容,无论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("来自Docker容器的anotherLink:%s", actual.Title)
    }
}
英文:

Please help me with the below as always the condition is exceuted irrespective of the type of json response. This is a sample public url returning json and we just log the title if the response conforms to the structure. However what ever json response is coming the code is going inside the condition(err ==nil). The json Decoder should be checking the structure of the response if i am not wrong.

my code complete below

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)

	}

答案1

得分: 3

默认情况下,没有对应结构字段的对象键将被忽略。使用DisallowUnknownFields可以使解码器对未知键返回错误。

d := json.NewDecoder(resp.Body)
d.DisallowUnknownFields()
if err = d.Decode(&actual); err == nil {
    fmt.Printf("来自Docker容器的anotherLink:%s", actual.Title)
}

这种方法的问题是结构类型必须包含服务器发送的每个字段。如果服务器在将来添加了新字段,解码将失败。

更好的选择是,如果未设置指定字段,则拒绝响应。

if err = json.NewDecoder(resp.Body).Decode(&actual); err != nil || actual.UserID == "" {
    // 处理错误响应。
}
英文:

By default, object keys which don't have a corresponding struct field are ignored. Use DisallowUnknownFields to cause the decoder to return an error for unknown keys.

d := json.NewDecoder(resp.Body)
d.DisallowUnknownFields()
if err = d.Decode(&actual); err == nil {
    fmt.Printf("anotherLink from docker container: %s", actual.Title)

}

The problem with this approach is that the struct type must include every field sent by the server. Decode will fail if the server adds a new field in the future.

A better option is to reject the response if specified fields are not set.

if err = json.NewDecoder(resp.Body).Decode(&actual); err != nil || actual.UserID == "" {
    // Handle bad response.
}

huangapple
  • 本文由 发表于 2021年12月8日 00:56:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/70264041.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定