Golang JSON 结构小写不起作用

我有一个结构:


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作为空字符串。但是如果我删除相应的标签,那么该字段将被发布


守候你守候我
浏览 324回答 2
2回答

翻过高山走不出你

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

精慕HU

基于示例文件,你在 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。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go