使用huandu/facebook Golang FB API时出现DecodeField错误。

huangapple go评论87阅读模式
英文:

DecodeField error when using huandu/facebook Golang FB api

问题

我正在尝试使用huandu/facebook Golang FB API在批量请求后使用Result.DecodeField提取FB用户信息、动态等。以下是一个简化版本,只包含一个批量请求。

我被这个问题困扰了一整天。如果你能帮忙检查一下这个问题,我将非常感激!

代码:

type User struct {
    Id   string `json:"id" facebook:"id"`
    Name string `json:"name" facebook:"name"`
}

func batchRequests() {

    paramsId := fb.Params{
        "method":       fb.GET,
        "relative_url": "me",
    }

    results, errBatch := pSession.BatchApi(paramsId)
    if errBatch != nil {
        fmt.Println("Batch api error:", errBatch.Error())
        return
    }

    fmt.Println("Results[0]:", results[0])

    var user User
    if err := results[0].DecodeField("body", &user); err != nil {
        fmt.Println("Decode user err:", err.Error())
    } else {
        fmt.Println("user", res0)
    }

    return
}

调试信息:

Results[0]: map[code:200 headers:[map[name:Last-Modified value:2014-05-26T02:20:09+0000] map[name:Facebook-API-Version value:v2.0] map[name:ETag value:"53abd9d236bfbd61662d1139e66983f8d0220d1e"] map[name:Content-Type value:text/javascript; charset=UTF-8] map[name:Pragma value:no-cache] map[name:Access-Control-Allow-Origin value:*] map[name:Cache-Control value:private, no-cache, no-store, must-revalidate] map[name:Expires value:Sat, 01 Jan 2000 00:00:00 GMT]] body:{"id":"10152276269XXXXXX","first_name":"XXXX","gender":"male","last_name":"XXXX","link":"https://www.facebook.com/app_scoped_user_id/1015227626XXXXXX/","locale":"zh_TW","name":"XXXXXX","timezone":8,"updated_time":"2014-05-26T02:20:09+0000","verified":true}]

Decode user err: 字段 'body' 在结果中不是一个 JSON 对象。

英文:

I was trying to extract FB user info, feed, etc. with Result.DecodeField after a batch request, by using huandu/facebook Golang FB api. Below is the simplified version with a single request in a batch.

I was blocked by this for a whole day. Deep appreciate if you can help check this problem!

code:

type User struct {
	Id    string `json:"id" facebook:"id"`
	Name  string `json:"name" facebook:"name"`
}

func batchRequests() {

	paramsId := fb.Params{
		"method":       fb.GET,
		"relative_url": "me",
	}

	results, errBatch := pSession.BatchApi(paramsId)
	if errBatch != nil {
		fmt.Println("Batch api error:", errBatch.Error())
		return
	}

	fmt.Println("Results[0]:", results[0])

	var user User
	if err := results[0].DecodeField("body", &user); err != nil {
		fmt.Println("Decode user err:", err.Error())
	} else {
		fmt.Println("user", res0)
	}

    return 
}

Debug msg:

Results[0]: map[code:200 headers:[map[name:Last-Modified value:2014-05-26T02:20:09+0000] map[name:Facebook-API-Version value:v2.0] map[name:ETag value:"53abd9d236bfbd61662d1139e66983f8d0220d1e"] map[name:Content-Type value:text/javascript; charset=UTF-8] map[name:Pragma value:no-cache] map[name:Access-Control-Allow-Origin value:*] map[name:Cache-Control value:private, no-cache, no-store, must-revalidate] map[name:Expires value:Sat, 01 Jan 2000 00:00:00 GMT]] body:{"id":"10152276269XXXXXX","first_name":"XXXX","gender":"male","last_name":"XXXX","link":"https://www.facebook.com/app_scoped_user_id/1015227626XXXXXX/","locale":"zh_TW","name":"XXXXXX","timezone":8,"updated_time":"2014-05-26T02:20:09+0000","verified":true}]

Decode user err: field 'body' is not a json object in result.

答案1

得分: 1

感谢OneOfOne的提示。以下是解决方案。

将以下代码替换为:

var user User
if err := results[0].DecodeField("body", &user); err != nil {
    fmt.Println("Decode user err:", err.Error())
} else {
    fmt.Println("user", res0)
}

替换为:

var user User
if body, ok := results[0]["body"].(string); ok {

    jsonDec := json.NewDecoder(strings.NewReader(body))
    if err := jsonDec.Decode(&user); err != nil {
        fmt.Println("err:", err.Error())
    } else {
        fmt.Println("decode user", user)
    }

} else {
    fmt.Println("results[0]'s body is not string")
}
英文:

Thank for OneOfOne's hint. Below is the solution.

Replace

var user User
if err := results[0].DecodeField("body", &user); err != nil {
    fmt.Println("Decode user err:", err.Error())
} else {
    fmt.Println("user", res0)
}

with

var user User
if body, ok := results[0]["body"].(string); ok {

	jsonDec := json.NewDecoder(strings.NewReader(body))
	if err := jsonDec.Decode(&user); err != nil {
		fmt.Println("err:", err.Error())
	} else {
		fmt.Println("decode user", user)
	}

} else {
	fmt.Println("results[0]'s body is not string")
}

答案2

得分: 1

图书馆文档误导了。Facebook在批量API响应中始终将“body”字段作为字符串返回。因此,“body”不能直接解码为用户结构。

我刚刚在库中添加了一个新的BatchResult结构,用于存储解析的批量API响应。以下是使用这个新结构解码User的示例。

// 省略了错误处理代码。
batchResult, _ := results[0].Batch()

var user User
batchResult.Result.Decode(&user)
fmt.Println("解码用户", user)

英文:

Library document was misleading. Facebook always returns a "body" field as string in batch api response. So "body" cannot be decoded to user struct directly.

I just add a new BatchResult struct in library to store a parsed batch api response. Here is a sample to use this new struct to decode User.

// error handling code is omitted.
batchResult, _ := results[0].Batch()

var user User
batchResult.Result.Decode(&user)
fmt.Println("decode user", user)

huangapple
  • 本文由 发表于 2014年7月29日 00:52:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/25000237.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定