gpt4 book ai didi

json - 当 slice 是响应的一部分时,将嵌套的数据响应展开为结构

转载 作者:行者123 更新时间:2023-12-01 22:30:42 26 4
gpt4 key购买 nike

我想对如何将嵌套的响应数据展开为自定义结构进行一些投入。以下是我返回的数据的示例。我正在尝试获取用户数据。

{
"_links": {
"self": {
"href": "/api/v2/user-search/default/test?after=1585612800000&limit=20&offset=0&q=johnsmith%40test.com",
"type": "application/json"
}
},
"totalCount": 1,
"items": [
{
"lastPing": "2020-04-30T02:56:10.430867577Z",
"environmentId": "xxxx",
"ownerId": "xxxx",
"user": {
"key": "johnsmith@test.com",
"email": "johnsmith@test.com",
"firstName": "john",
"lastName": "smith"
},
"_links": {
"parent": {
"href": "/api/v2/users/default/test",
"type": "application/json"
},
"self": {
"href": "/api/v2/users/default/test/johnsmith@test.com",
"type": "application/json"
},
"settings": {
"href": "/api/v2/users/default/test/johnsmith@test.com/flags",
"type": "text/html"
},
"site": {
"href": "/default/test/users/johnsmith@test.com",
"type": "text/html"
}
}
}
]
}

目前我正在做以下
respData := map[string][]map[string]map[string]interface{}{}
json.Unmarshal(respBody, &respData)

userData := respData["items"][0]["user"]

我希望能够将其解编为自定义结构,但似乎无法使其正常工作。用户对象所在的嵌套 slice 一直使我失望。

最佳答案

type User struct {
Key string `json:"key"`
Email string `json:"email"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
}

type LinkInfo struct {
Href string `json:"href"`
Type string `json:"type"`
}

type Item struct {
LastPing time.Time `json:"lastPing"`
EnvironmentID string `json:"environmentId"`
OwnerID string `json:"ownerId"`
User User `json:"user"`
Links LinkInfo `json:"_links"`
Self LinkInfo `json:"self"`
Settings LinkInfo `json:"settings"`
Parent LinkInfo `json:"parent"`
Site LinkInfo `json:"site"`
}

type ItemDetails struct {
Links LinkInfo `json:"_links"`
TotalCount int `json:"total_count"`
Items []Item
}

你可以试试这个吗?

https://play.golang.org/p/S_CUN0XEh-d

关于json - 当 slice 是响应的一部分时,将嵌套的数据响应展开为结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61516013/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com