LoginSignup
15
15

More than 5 years have passed since last update.

GoでJSONシリアライズ・デシリアライズ

Last updated at Posted at 2013-05-28

GoでJSONのシリアライズ・デシリアライズ

こういう形のJSONデータをやり取りする機会があったのですが、このやり取りに、今回はGoを使ってみました。

JSON
{"items":[
  {"text":"name","value":0},
  {"text":"name","value":1},
  {"text":"name","value":2},
  {"text":"name","value":3},
  {"text":"name","value":4}
]}

シリアライズ

まずは上記のJSON構造に合ったstructを作ります。Goの変数命名規則が問題で必要なJSONの形式に出力できない場合は、変数の型のうしろにタグを付けて任意の名前を付けます。

//繰り返し要素
type ApiItem struct {
    Text   string `json:"text"`
    Value  int `json:"value"`
}

//root
type ApiList struct {
    Items []ApiItem `json:"items"`
}

このstructを用いてデータを生成し、encoding/jsonパッケージのjson.Marshalを使えばJSONデータが作られます。

    apiList := ApiList{make([]ApiItem, 0, 10)}

    for i := 0; i < 5; i++ {
        apiList.Items = append(apiList.Items, ApiItem{"name", i})
    }

    formatBytes, err := json.Marshal(apiList)
    if err != nil {
        fmt.Println(err)
    }

    output := string(formatBytes)
    fmt.Println(output)

json.Marshalで得られる型は[]byteですので、読みやすいように文字列化して出力すると、こういうかたちになります。

JSON
{"items":[{"text":"name","value":0},{"text":"name","value":1},{"text":"name","value":2},{"text":"name","value":3},{"text":"name","value":4}]}

デシリアライズ

逆にJSONデータを受け取り変数にマッピングする場合は、json.Unmarshalを使えば良いです。

    data := ApiList{}
    err = json.Unmarshal(formatBytes, &data)
    if err != nil {
        fmt.Println(err)
    }

    for _, item := range data.Items {
        fmt.Printf("text : %s, value = %d\n", item.Text, item.Value)
    }

json.Unmarshalの第1引数には[]byte型のJSONデータ、第2引数にはJSONデータをデシリアライズして格納したい変数へのポインタを渡します。

結果はこんな感じ。ちゃんと格納されているようです。

text : name, value = 0
text : name, value = 1
text : name, value = 2
text : name, value = 3
text : name, value = 4

Go標準のライブラリだけで、JSONのシリアライズ・デシリアライズを簡単に書くことができます。

15
15
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
15