dpjjr42626 2015-02-12 00:38
浏览 50
已采纳

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

As part of an Oauth application, I need to decode some JSON. But I cannot get the object populated. There is no failure, but the data just isn't there. I've tried a bunch of different ways...

I have recreated the problem at 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)
    }
}
  • 写回答

1条回答 默认 最新

  • 普通网友 2015-02-12 01:19
    关注

    The JSON encoding package works with exported fields only. Capitalize the field names to export them:

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办