英文:
JSON decode specific field golang
问题
我有一个简单的函数,从特定的URI获取JSON响应。该函数接受httpRequest
和interface{}
作为参数,其中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 ,
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论