dongshetao1814 2015-02-09 13:56
浏览 857
已采纳

Golang和JSON与结构体数组

I would like to create a JSON of a GatewayInfo where the type are defined like this:

type SpanInfo struct {
    imsi string
    network string
    network_status string
    signal_quality int
    slot int
    state string
}

type GatewayInfo []SpanInfo

The gateway information is created with:

var gatewayInfo = make(GatewayInfo, nb_spans)

To create the JSON, I use the json.Marshal function:

gatewayInfo := getGatewayInfo(spans)
log.Printf("Polling content: %s
", gatewayInfo)

jsonInfo, _ := json.Marshal(gatewayInfo)
log.Printf("jsonInfo: %s
", jsonInfo)

Unfortunately the result is not what I was expecting:

2015/02/09 13:48:26 Polling content: [{652020105829193 20801 Registered (Roaming) %!s(int=17) %!s(int=2) } {652020105829194 20801 Registered (Roaming) %!s(int=16) %!s(int=3) } {652020105829192 20801 Registered (Roaming) %!s(int=19) %!s(int=1) } {652020105829197 20801 Registered (Roaming) %!s(int=19) %!s(int=4) }]
2015/02/09 13:48:26 jsonInfo: [{},{},{},{}]

As we can see, the GatewayInfo instance has the SpanInfo, but in the JSON I have empty SpanInfo.

  • 写回答

2条回答 默认 最新

  • duanchi6397 2015-02-09 14:06
    关注

    Your struct fields must be exported (field is exported if it begins with a capital letter) or they won't be encoded:

    Struct values encode as JSON objects. Each exported struct field becomes a member of the object

    To get the JSON representation as probably expected change the code to this:

    type SpanInfo struct {
        IMSI string `json:"imsi"`
        Network string `json:"network"`
        NetworkStatus string `json:"network_status"`
        SignalQuality int `json:"signal_quality"`
        Slot int `json:slot"`
        State string `json:"state"`
    }
    
    type GatewayInfo []SpanInfo
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?