20
votes

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\n", gatewayInfo)

jsonInfo, _ := json.Marshal(gatewayInfo)
log.Printf("jsonInfo: %s\n", 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.

3

3 Answers

39
votes

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
9
votes

The json package can only serialize exported fields of your struct. Change your struct to start all fields with an uppercase letter so they can be included in the output:

type SpanInfo struct {
    Imsi string
    Network string
    Network_status string
    Signal_quality int
    Slot int
    State string
}

Read the documentation of json.Marshal() for details and more information.

0
votes

This is not a new answer. It is just consolidation of comments on the accepted answer.


From ORIGINAL Query

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

From Answer and comments - Please note that the first char of each field in struct is now in UPPER case along with json representation added to each field

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"`
}