1 回答
TA贡献1993条经验 获得超5个赞
{
"status": 200,
"msg": "OK",
"result": {
24: {
"id": 24,
"remoteurl": "http://proof.ovh.net/files/100Mio.dat",
"status": "new",
"bytes_loaded": null,
"bytes_total": null,
"folderid": "4248",
"added": "2015-02-21 09:20:26",
"last_update": "2015-02-21 09:20:26",
"extid": false,
"url": false
}
}
}
不是值 JSON。你必须指的是我在下面发布的 JSON,如果你想检查自己,请将你的 JSON 版本复制到任何 JSON 验证器中;
https://jsonlint.com/
https://jsoneditoronline.org/
https://jsonformatter.curiousconcept.com/
另请查看下面链接的线程。如果 API 确实返回了您声称返回的内容,则该 API 中存在错误
为什么 JSON 只允许字符串作为键?
{
"status": 200,
"msg": "OK",
"result": {
"24": {
"id": 24,
"remoteurl": "http://proof.ovh.net/files/100Mio.dat",
"status": "new",
"bytes_loaded": null,
"bytes_total": null,
"folderid": "4248",
"added": "2015-02-21 09:20:26",
"last_update": "2015-02-21 09:20:26",
"extid": false,
"url": false
}
}
}
下面是一些使用映射到结构的示例代码,它解决了第二个响应的动态响应
package main
import (
"encoding/json"
"fmt"
"log"
)
var res1 = `{
"status": 200,
"msg": "OK",
"result": {
"id": "24",
"folderid": "4248"
}
}`
var res2 = `{
"status": 200,
"msg": "OK",
"result": {
"24": {
"id": 24,
"remoteurl": "http://proof.ovh.net/files/100Mio.dat",
"status": "new",
"bytes_loaded": null,
"bytes_total": null,
"folderid": "4248",
"added": "2015-02-21 09:20:26",
"last_update": "2015-02-21 09:20:26",
"extid": false,
"url": false
}
}
}
`
type One struct {
Status int `json:"status"`
Msg string `json:"msg"`
Result struct {
ID string `json:"id"`
Folderid string `json:"folderid"`
} `json:"result"`
}
type Two struct {
Status int `json:"status"`
Msg string `json:"msg"`
Result map[string]innerData `json:"result"`
}
type innerData struct {
ID int `json:"id"`
Remoteurl string `json:"remoteurl"`
Status string `json:"status"`
BytesLoaded interface{} `json:"bytes_loaded"`
BytesTotal interface{} `json:"bytes_total"`
Folderid string `json:"folderid"`
Added string `json:"added"`
LastUpdate string `json:"last_update"`
Extid bool `json:"extid"`
URL bool `json:"url"`
}
func main() {
var one One
err := json.Unmarshal([]byte(res1), &one)
if err != nil {
log.Fatal(err)
}
var two Two
err = json.Unmarshal([]byte(res2), &two)
if err != nil {
log.Fatal(err)
}
//pretty print both strutures
b, _ := json.MarshalIndent(one, "", " ")
fmt.Printf("%s \n\n", b)
b, _ = json.MarshalIndent(two, "", " ")
fmt.Printf("%s \n\n", b)
// access data from two with id from one
if dat, ok := two.Result[one.Result.ID]; ok {
b, _ = json.MarshalIndent(dat, "", " ")
fmt.Printf("inner data\n%s\n", b)
}
}
- 1 回答
- 0 关注
- 87 浏览
添加回答
举报