Golang将JSON结构体转换为小写不起作用。

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

Golang JSON struct to lowercase doesn't work

问题

我有一个结构体:

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"
}

但是,如果我删除其中一个标签(即删除ApplicationIdApplicationKey标签),那么该字段就会显示出来。

这是我设置结构体的方式:

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_idapplication_key都是空字符串。但是,如果我删除相应的标签,那么该字段就会被发送。

英文:

I have a struct:

type Credentials struct {
	Username 	string	`json:"username"`
	Password	string	`json:"password"`
	ApplicationId	string	`json:"application_id"`
	ApplicationKey	string	`json:"application_key"`
}

And I've tagged my fields to lowercase them.

However, whenever I include the application tags, those fields become null, i.e. on my POST request I get

{ application_id: '',
  application_key: '',
  password: 'myPassword',
  username: 'myUsername' 
}

But if I remove either of the tag (so remove ApplicatinonId or ApplicationKey tag), then that field does show up

Here is how I set my struct:

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
}

My credential json file is:

{
  "Username": "myUsername",
  "Password": "myPassowrd",
  "ApplicationId": "someID",
  "ApplicationKey": "someString"
}

Then, I post my data with:

credentials := getCredentials()
url := GetLoginURL()

resp, body, requestErr := gorequest.New().
	Post(url).
	Send(credentials).
	End()

But on the server, I get both application_id and application_key as empty strings. But if I remove the corresponding tag, then that field is posted

答案1

得分: 2

看起来你的凭证文件是错误的(它需要使用 application_id 和 application_key 这两个键 - Go 足够聪明可以识别大小写,但不能识别下划线):

{
  "Username": "我的用户名",
  "Password": "我的密码",
  "application_id": "某个ID",
  "application_key": "某个字符串"
}
英文:

It looks like your credential file is wrong (it needs to use the keys application_id and application_key - Go is smart enough to figure out the capitalization, but not underscores):

{
  "Username": "myUsername",
  "Password": "myPassowrd",
  "application_id": "someID",
  "application_key": "someString"
}

答案2

得分: 0

根据示例文件,你在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函数报错。

英文:

Based off the example file your struct in Go should look like this;

type Credentials struct {
    Username    string  `json:"Username"`
    Password    string  `json:"Password"`
    ApplicationId   string  `json:"ApplicationId"`
    ApplicationKey  string  `json:"ApplicationKey"`
}

You could also approach this from the other end and modify the entries in your file to look like this;

{
  "Username": "myUsername",
  "Password": "myPassowrd",
  "application_id": "someID",
  "application_key": "someString"
}

However, it's more often the case that you can't change the data you're receiving (like when calling a third party API) so you usually end up changing your source. Since you control the file and the API wants lower case I'd recommend changing the files contents to match what you send the API. The other option which is sometimes necessary is to use another type and provide a conversion helper (assuming you controlled neither the file nor the API, you'd need different types for each). The Go encoding packages are very strict. You may be used to things like json.NET which will assign near matches, that isn't the case here. Anything less than an exact match will yield an error from Unmarshal.

huangapple
  • 本文由 发表于 2016年3月26日 01:25:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/36224779.html
匿名

发表评论

匿名网友

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

确定