[英]JSON decode specific field golang
我有这个简单的 function,它从特定 URI 获得 JSON 响应。 function 接受httpRequest
和一个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
object。对于这个 object,解码操作失败,因为 object 不包含在我的结构中。 我想直接解码data
object 的内容,而不使用临时结构,但我不知道该怎么做。
使用包含要解组到的User
结构的结构。 请参阅下面的响应结构。
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)
PS:您的代码在 json 标签处有错字。 替换;
通过,
我有这个简单的 function,它从特定的 URI 获得 JSON 响应。 function 接受httpRequest
和一个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
object。 使用这个 object,解码操作失败,因为 object 它不包含在我的结构中。 我想直接解码data
object 的内容,不使用临时结构,但我不明白该怎么做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.