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

Golang JSON 结构小写不起作用

Golang JSON 结构小写不起作用

Go
守候你守候我 2021-12-27 17:01:05
我有一个结构:type Credentials struct {    Username    string  `json:"username"`    Password    string  `json:"password"`    ApplicationId   string  `json:"application_id"`    ApplicationKey  string  `json:"application_key"`}我已经标记了我的字段以小写它们。但是,每当我包含应用程序标签时,这些字段都会变为空,即在我的 POST 请求中,我得到{ application_id: '',  application_key: '',  password: 'myPassword',  username: 'myUsername' }但是如果我删除任何一个标签(因此删除ApplicatinonId或ApplicationKey标记),那么该字段确实会显示这是我设置结构的方法:func getCredentials() Credentials {    raw, err := ioutil.ReadFile(os.Getenv("BASE_PATH") + FILE_Credentials)    if err != nil {        log.Warn("Could not read credentials file: %s", err.Error())        os.Exit(1)    }    var credentials Credentials    json.Unmarshal(raw, &credentials)    return credentials}我的凭证json文件是:{  "Username": "myUsername",  "Password": "myPassowrd",  "ApplicationId": "someID",  "ApplicationKey": "someString"}然后,我发布我的数据:credentials := getCredentials()url := GetLoginURL()resp, body, requestErr := gorequest.New().    Post(url).    Send(credentials).    End()但是在服务器上,我同时得到application_id和application_key作为空字符串。但是如果我删除相应的标签,那么该字段将被发布
查看完整描述

2 回答

?
翻过高山走不出你

TA贡献1875条经验 获得超3个赞

看起来你的凭证文件是错误的(它需要使用键 application_id 和 application_key - Go 足够聪明来计算大写,但不是下划线):


{

  "Username": "myUsername",

  "Password": "myPassowrd",

  "application_id": "someID",

  "application_key": "someString"

}


查看完整回答
反对 回复 2021-12-27
?
精慕HU

TA贡献1845条经验 获得超8个赞

基于示例文件,你在 Go 中的结构应该是这样的;


type Credentials struct {

    Username    string  `json:"Username"`

    Password    string  `json:"Password"`

    ApplicationId   string  `json:"ApplicationId"`

    ApplicationKey  string  `json:"ApplicationKey"`

}

您也可以从另一端处理此问题,并将文件中的条目修改为如下所示;


{

  "Username": "myUsername",

  "Password": "myPassowrd",

  "application_id": "someID",

  "application_key": "someString"

}

但是,更常见的情况是您无法更改接收的数据(例如调用第三方 API 时),因此您通常最终会更改源。由于您控制文件并且 API 需要小写,我建议更改文件内容以匹配您发送 API 的内容。有时需要的另一个选项是使用另一种类型并提供转换帮助程序(假设您既不控制文件也不控制 API,则每个类型都需要不同的类型)。Go 编码包非常严格。您可能已经习惯了 json.NET 之类的东西,它会分配接近的匹配项,但这里的情况并非如此。任何不完全匹配的东西都会产生一个错误Unmarshal。


查看完整回答
反对 回复 2021-12-27
  • 2 回答
  • 0 关注
  • 313 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号