JSON decode specific field golang

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

JSON decode specific field golang

问题

我有一个简单的函数,从特定的URI获取JSON响应。该函数接受httpRequestinterface{}作为参数,其中interface{}是我想要将JSON响应解组到的结构体的指针。

func (c *Client) SendRequest(req *http.Request, v interface{}) error {
      ...
      
      return json.NewDecoder(resp.Body).Decode(&v)
}

JSON响应的示例是:

{
  "data": {
    "id": "9da7a204-544e-5fd1-9a12-61176c5d4cd8"
  }
}

结构体的示例是:

type User struct {
    ID string `json:"id,omitempty"`
}

现在的问题是data对象。由于该对象未包含在我的结构体中,解码操作会失败。我想直接解码data对象的内容,而不使用临时结构体,但我不知道如何做到。

英文:

I have this simple function, which gets a JSON response from a specific URI. The function accepts the httpRequest and an interface{}, which is a pointer to the struct in which I want to unmarshal my JSON response.

func (c *Client) SendRequest(req *http.Request, v interface{}) error {
      ...
      
      return json.NewDecoder(resp.Body).Decode(&v)
}

An example of JSON response is:

{
  "data": {
    "id": "9da7a204-544e-5fd1-9a12-61176c5d4cd8"
  }
}

An example of struct is:

type User struct {
		ID	string `json:"id;omitempty"`
	}

Now, the problem is the data object. With this object, the Decode operation fails, as the object it is not included in my struct. I would like to Decode the content of data object directly, without using a temporary struct, but I don't understand how to do it.

答案1

得分: 2

使用一个包含User结构体的结构体进行解组。请参考下面的Response结构体。

type User struct {
	ID string `json:"id,omitempty"`
}

type Response struct {
	Data User `json:"data"`
}

解组后,如果r是你的Response实例,你可以通过r.Data访问你的User

由于在编译时你不知道类型,你也可以将字段的类型设置为interface{}

type Response struct {
	Data interface{} `json:"data"`
}

r := Response{
	Data: &User{},
}

json.NewDecoder(resp.Body).Decode(&r)

然后通过以下方式获取你的用户实例:

userNew, _ := r.Data.(*User)

附注:你的代码中的json标签有一个拼写错误。请将;替换为,

英文:

Use a struct that contains a User struct to unmarshal into. See Response struct below.

type User struct {
	ID string `json:"id;omitempty"`
}

type Response struct {
	Data User `json:"data"`
}

After unmarshaling if r is your Response instance you can access your User by r.Data

Since you don't know the type at compile time you can use interface{} as the type of the field too.

type Response struct {
	Data interface{} `json:"data"`
}

r := Response{
	Data: &User{},
}

json.NewDecoder(resp.Body).Decode(&r)

And then get your user instance by

userNew, _ := r.Data.(*User)

P.S: You have a typo on your code at json tag. Replace ; by ,

huangapple
  • 本文由 发表于 2021年5月21日 19:17:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/67635798.html
匿名

发表评论

匿名网友

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

确定