我想创建一个GatewayInfo的
JSON,其类型定义如下:
type SpanInfo struct { imsi string network string network_status string signal_quality int slot int state string } type GatewayInfo []SpanInfo
网关信息创建于:
var gatewayInfo = make(GatewayInfo,nb_spans)
要创建JSON,我使用json.Marshal函数:
gatewayInfo := getGatewayInfo(spans) log.Printf("Polling content: %s\n",gatewayInfo) jsonInfo,_ := json.Marshal(gatewayInfo) log.Printf("jsonInfo: %s\n",jsonInfo)
不幸的是结果不是我所期待的:
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: [{},{},{}]
我们可以看到,GatewayInfo实例有SpanInfo,但在JSON中我有空的SpanInfo.
您的结构字段必须导出(如果以大写字母开头,则导出字段)或者不对其进行编码:
原文链接:https://www.f2er.com/go/186784.htmlStruct values encode as JSON objects. Each exported struct field
becomes a member of the object
要获得可能需要的JSON表示,请将代码更改为:
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