duanpen9294 2015-09-20 01:40
浏览 100
已采纳

为什么结构字段显示为空?

I am struggling to get the correct output from the following code:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {

    var jsonBlob3 = []byte(`[
        {"name": "Platypus", "spec": "Monotremata", "id":25 },
        {"name": "Quoll",    "spec": "Dasyuromorphia", "id":25 }
    ]`)
    type Animal2 struct {
        name  string
        spec string
        id uint32
    }
    var animals []Animal2
    err := json.Unmarshal(jsonBlob3, &animals)
    if err != nil {
        fmt.Println("error:", err)
    }
    fmt.Printf("%+v
", animals)
}

Playground snippet

The struct fields are empty when printed. I am sure there is a dumb mistake somewhere but I am still new to Go and I have been stuck at this for hours. Please help.

  • 写回答

1条回答 默认 最新

  • dongmi3203 2015-09-20 01:45
    关注

    This has come up so many times. The problem is that only exported fields can be marshaled/unmarshaled.

    Export the struct fields by starting them with capital (upper-case) letters.

    type Animal2 struct {
        Name  string
        Spec string
        Id uint32
    }
    

    Try it on the Go Playground.

    Note that the JSON text contains the field names with lowercased text, but the json package is "clever" enough to match them. If they would be completely different, you could use struct tags to tell the json package how they are found (or how they should be marshaled) in the JSON text, e.g.:

    type Animal2 struct {
        Name  string `json:"json_name"`
        Spec string  `json:"specification"`
        Id uint32    `json:"some_custom_id"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)