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

标签 json go

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

{
  "_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/

相关文章:

php - 通过PHP从Json获取 channel 主页URL

Golang 虹膜 : Initialize parent controller's model to child controller's model

docker - 从数据流中解码 JSON Docker GO SDK

google-app-engine - 如何根据项目ID设置变量?

templates - tmpl.执行并分文件golang

go - 使用 Flyspell-prog-mode 和 go-autocomplete

php - 输出 JSON 时网页未加载 PHP-MySQL 代码

java - 如何区分 Spring Rest Controller 中部分更新的 null 值和未提供的值

java - 如何在 spring MVC 的 Controller 中操作 jQuery AJAX JSON 数据

php - 处理 PHP JSON 对象中的数据