[英]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.