为了账号安全,请及时绑定邮箱和手机立即绑定

Unmarshal 只给我嵌套在 JSON 响应中的数组的第一个元素

Unmarshal 只给我嵌套在 JSON 响应中的数组的第一个元素

Go
三国纷争 2022-01-17 10:10:18
我正在尝试使用 Flickr API,并且我有一个端点,它给了我这样的响应{  "photos": {    "page": 1,    "pages": 500,    "perpage": 1,    "total": 500,    "photo": [      {        "id": "12345",        "owner": "12345@N01",        "secret": "12ab345xyz",        "server": "1234",        "farm": 1,        "title": "Some Title",        "ispublic": 1,        "isfriend": 0,        "isfamily": 0      },     ...    ]  },  "stat": "ok"}我有一个看起来像这样的结构type FlickrResp struct {    Photos struct {        Page int            `json:"page"`       //what page the results were retreived from        Pages int           `json:"pages"`      //total number of pages of results        Perpage int         `json:"perpage"`    //number of results per page        Total int           `json:"total"`      //total number of results        }                   `json:"photo"`      //array of objects with details of photos    }                       `json:"photos"`     //object that holds information about photoset    Stat string             `json:"stat"`       //status}我正在尝试解组var fr FlickrResp                                               //create blank struct of type FlickrResp to hold JSONresp, err := ioutil.ReadAll(flickrCB.Body)                      //read HTTP GET responseif err != nil {}json.Unmarshal([]byte(resp), &fr)                               //serialize JSON into templateflickCB.Body 来自一个 http.Get问题是我只得到照片数组的第一个元素。当我打印转换为字符串的响应对象时,我可以看到我有多个元素。我究竟做错了什么?几天来,我一直在反对 Unmarshal 和更复杂的 JSON 响应。
查看完整描述

1 回答

?
郎朗坤

TA贡献1921条经验 获得超9个赞

最初在评论中回答,但需要更多说明:


有一个未捕获的错误来自json.Unmarshal:


json: cannot unmarshal number into Go value of type string


由于闪烁 API 之间的类型不匹配导致ispublic, isfriend, 和isfamily作为整数,但结构期待字符串。一个简单的解决方法是将它们转换为整数。


这种情况的另一种选择是使用json.Number,它包装来自源 json 的基本字符串,并提供一些方便的方法来稍后将其转换为数字(或将其保留为字符串)。通过说


Ispublic json.Number `json:"ispublic"`   //is image publicly viewable?

Isfriend json.Number `json:"isfriend"`   //is image owner my friend?

Isfamily json.Number `json:"isfamily"`

它可以正常工作,并且可以通过fr.Ispublic.String().


在这种情况下可能有用的更精细的更改是使用自定义布尔类型。有问题的值似乎反映了布尔值,但整数也不能干净地映射到布尔值。可以使用自定义反序列化类型。借用stackoverflow其他地方的这个例子:


type ConvertibleBoolean bool


func (bit ConvertibleBoolean) UnmarshalJSON(data []byte) error {

    asString := string(data)

    if asString == "1" || asString == "true" {

        bit = true

    } else if asString == "0" || asString == "false" {

        bit = false

    } else {

        return errors.New(fmt.Sprintf("Boolean unmarshal error: invalid input %s", asString))

    }

    return nil

}

以上将允许您将Is*值声明为ConvertibleBoolean,并将自动将您可能在 Flickr 的这些字段中获得的 0 和 1 值映射到布尔值。


查看完整回答
反对 回复 2022-01-17
  • 1 回答
  • 0 关注
  • 230 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信