【问题标题】:Grabbing value from Confluence JSON response从 Confluence JSON 响应中获取价值
【发布时间】:2019-10-21 13:11:53
【问题描述】:

我正在尝试从汇合页面的 JSON 响应中获取 ID 字段,该数据如下所示:

`{"results":[{"id":"89425836","type":"page","status":"current","title":"string","extensions":{"position":"none"},"_links":{"webui":"/web/url","edit":"/pages/resumedraft.action?draftId=89425836","tinyui":"/x/rIdUBQ","self":"https://confluence.domain.org/rest/api/content/89425836"},"_expandable":{"container":"/rest/api/space/spaceName","metadata":"","operations":"","children":"/rest/api/content/89425836/child","restrictions":"/rest/api/content/89425836/restriction/byOperation","history":"/rest/api/content/89425836/history","ancestors":"","body":"","version":"","descendants":"/rest/api/content/89425836/descendant","space":"/rest/api/space/spaceName"}}],"start":0,"limit":25,"size":1,"_links":{"self":"https://confluence.domain.org/rest/api/content?spaceKey=spaceName&type=page&title=title","base":"https://confluence.domain.org","context":""}}`

我一直在网上寻找,我的代码应该可以正常工作,但事实并非如此,我很茫然。

package main

import (
    "encoding/json"
    "net/http"
    "fmt"
    "io/ioutil"
)

type dataResponse struct {
    Id string `json:"id"`
}

func main() {

    var p dataResponse

    response, err := http.Get("https://confluence.domain.org/url/to/page/with/params"

    if err != nil {
       panic(err)
    } else {
      data, _ := ioutil.ReadAll(response.Body)
      json.Unmarshal(data, &p)
      fmt.Println(p.Id)
    }

   defer response.Body.Close()
}

但这并没有返回任何东西。我认为这与 id 字段在“结果”之后有关,但还没有找到解决方法。编辑:更新的网址,不小心复制了调试。

【问题讨论】:

    标签: json go confluence-rest-api


    【解决方案1】:

    id 位于results 内部的对象数组中。要解组 json 文档,您的结构必须与文档匹配,即:

    type body struct {
      Results []dataResponse `json:"results"`
    }
    

    然后:

    var doc body
    json.Unmarshal(data, &doc)
    

    您可以从以下地址获取id

    doc.Results[i].Id
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多