golang中struct变量JSON转码变量名必须大写

Golang中struct变量在进行JSON转码时,若变量名首字母小写,则不可被外部访问。通过测试发现,小写的变量在转码过程中其值未传递。解决方法是将struct变量名改为首字母大写,以确保其对外可见,从而正确转码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在进行struct变量转码时,发现不管我传入的是什么值,最后传回的都是{}
于是写了一个测试代码,如下进行验证。

package main

import (
    "encoding/json"
    "fmt"
)

type test struct {
    institutionID string `json:"institution_id"`
    userID string `json:"user_id"`
    dateTime string `json:"date_time"`
    type1 string `json:"type"`
    sum string `json:"sum"`// negative for withdraw, positive for top
}

func main() {
    var args = []string{"12","23","34","45","56"}
    var h = test{institutionID:args[0],userID:args[1],dateTime:args[2],type:args[3],sum:args[4]}
    hAsBytes,_ := json.Marshal(h)
    fmt.Print(hAsBytes)
}

得到的还是{}
然后断点调试了一下,发现h中的值根本没有传入到json.Marshal中进行转码。
原来golang对变量是否包外可访问,是通过变量名的首字母是否大小写来决定的,所以只要我们把struct中的变量名改为大写即可。
更改后代码如下

package main

import (
    "encoding/json"
    "fmt"
)

type test struct {
    InstitutionID string `json:"institution_id"`
    UserID string `json:"user_id"`
    DateTime string `json:"date_time"`
    Type string `json:"type"`
    Sum string `json:"sum"`// negative for withdraw, positive for top
}

func main() {
    var args = []string{"12","23","34","45","56"}
    var h = test{InstitutionID:args[0],UserID:args[1],DateTime:args[2],Type:args[3],Sum:args[4]}
    hAsBytes,_ := json.Marshal(h)
    fmt.Print(hAsBytes)
}

这样我们就得到了正确的转码值

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值