json - 在 Golang 中解析 JSON 不会填充对象

标签 json go

<分区>

作为 Oauth 应用程序的一部分,我需要解码一些 JSON。但是我无法填充对象。没有失败,但数据不存在。我尝试了很多不同的方法...

我在 http://play.golang.org/p/QGkcl61cmv 重现了这个问题

import (
    "encoding/json"
    "fmt"
    "strings"
   )

type RefreshTokenData struct {
    id            string `json:"id"`
    issued_at     string `json:"issued_at"`
    scope         string `json:"scope"`
    instance_url  string `json:"instance_url"`
    token_type    string `json:"token_type"`
    refresh_token string `json:"refresh_token"`
    signature     string `json:"signature"`
    access_token  string `json:"access_token"`
}

func main() {
    var tokenResp = `
    {"id":"https://google.com","issued_at":"1423698767063",
    "scope":"full refresh_token",
    "instance_url":"https://na15.salesforce.com",
    "token_type":"Bearer",
    "refresh_token":"2os53__CCU5JX_yZXE",
    "id_token":"5jSH0Oqm7Q4fc0xkE9NOvW8cA13U",
    "signature":"/599EkGVIBsKPFRNkg+58wZ3Q7AFyclvIGvCrxVeyTo=",
    "access_token":"sadfasdfasdfasdfdsa"}`

    var tokenData RefreshTokenData
    decoder := json.NewDecoder(strings.NewReader(tokenResp))
    if jsonerr := decoder.Decode(&tokenData); jsonerr != nil {
        fmt.Println("****Failed to decode json")
    } else {
        fmt.Println("****Refresh token: " + tokenData.refresh_token)
    }
}

最佳答案

JSON encoding packageexported fields 一起工作只要。将字段名称大写以将其导出:

type RefreshTokenData struct {
  Id            string `json:"id"`
  Issued_at     string `json:"issued_at"`
  Scope         string `json:"scope"`
  Instance_url  string `json:"instance_url"`
  Token_type    string `json:"token_type"`
  Refresh_token string `json:"refresh_token"`
  Signature     string `json:"signature"`
  Access_token  string `json:"access_token"`
}

playground example

关于json - 在 Golang 中解析 JSON 不会填充对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28467302/

相关文章:

json:无法将数组解码为 main.Data 类型的 Go 值

php - 为什么回显 JSON 编码数组不会产生任何输出

jquery - 根据单元格中的数据库数据更改表数据单元格的颜色

javascript - 如何将 JSON 变量更改为 3 个具有相同值的变量?

go - 了解 Go channel 死锁

json - 自定义 Json 编码(marshal)处理

json - 如何将 slf4j-over-logback 日志写为 JSON

c# - 将 Json 数组解析为 C# 中的类

json - 如何在结构中存储对象

go - 在 channel 上发送指针是否不安全?如果是,那为什么?