1

i want to serialize a struct to json, i wrote below code, but always return empty, did not figure it out.

you can try below code here: http://play.golang.org/p/Y7Zv_aFbqs

package main

import (
    "encoding/json"
    "fmt"
    //"io/ioutil"
)

type Configitem struct {
    local_address string
    local_port    int
    method        string
    password      string
    server        string
    server_port   string
    timeout       int
}

type GuiConfig struct {
    configs []*Configitem
    index   int
}

func main() {

    item1 := &Configitem{
        local_address: "eouoeu",
        local_port:    111,
        method:        "eoeoue",
        password:      "ouoeu",
        server:        "oeuoeu",
        server_port:   "qoeueo",
        timeout:       3333,
    }

    config1 := &GuiConfig{
        index:   1,
        configs: []*Configitem{item1}}

    fmt.Println(config1.configs[0].local_address)

    res2, err := json.Marshal(config1)
    check(err)
    fmt.Println(string(res2))
}

func check(e error) {
    if e != nil {
        panic(e)
    }
}

always return {}, i checked this link http://blog.golang.org/json-and-go, did not know why? what's wrong to my code.

Bill.Zhuang
  • 657
  • 7
  • 16

1 Answers1

4

Because json.Marshal is in another package, it only has access to exported fields. If you export the fields it works: http://play.golang.org/p/EMGm5-hs8g

Your other option is to implement the MarshalJson interface yourself (if you don't want to export the fields): http://play.golang.org/p/9gGOBuGbVu

dave
  • 62,300
  • 5
  • 72
  • 93