dongqing8765 2017-07-25 20:43
浏览 60
已采纳

转到json.unmarshal字段案例

I'm new to Go. I was trying to fetch and marshal json data to a struct. My sample data looks like this:

var reducedFieldData = []byte(`[
    {"model":"Traverse","vin":"1gnkrhkd6ej111234"}
    ,{"model":"TL","vin":"19uua66265a041234"}
]`)

If I define the struct for receiving the data like this:

type Vehicle struct {
    Model string
    Vin   string
}

The call to Unmarshal works as expected. However, if I use lower case for the fields ("model" and "vin") which actually matches cases for the field names in the data it will return empty strings for the values.

Is this expected behavior? Can the convention be turned off?

  • 写回答

1条回答 默认 最新

  • duancanjiu3754 2017-07-25 20:47
    关注

    Fields need to be exported (declared with an uppercase first letter) or the reflection library cannot edit them. Since the JSON (un)marshaller uses reflection, it cannot read or write unexported fields.

    So yes, it is expected, and no, you cannot change it. Sorry.

    You can add tags to a field to change the name the marshaller uses:

    Model string `json:"model"`
    

    See the documentation for more info on the field tags "encoding/json" supports.

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

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答