Golangカスタムjsonエクスポートフィールド名

2016 ワード

Golangカスタムjsonエクスポートフィールド名
show code:
package main

import (
    "encoding/json"
    "fmt"
)

func main () {
    student := Student{
        Name: "Leego",
        age:  18,
        Sex:  true,
    }
    data, e := json.MarshalIndent(student, " ", "")
    if e != nil {
        fmt.Println(e)
    }
    fmt.Println(string(data))
}

type Student struct {
    Name string  `json:"nameJson"`
    age int     `json:"ageJson"`
    Sex bool    `json:"  "`
}


出力結果は次のとおりです.
{
 "nameJson": "Leego",
 "  ": true
 }

なぜjson.MarshalIndent(student, " ", "")関数を使うのか、後の2つのパラメータはどういう意味ですか.ちょっと手を加えてみればわかるdata, e := json.MarshalIndent(student, " ", "")data, e := json.MarshalIndent(student, "~", "#")に変更しました
入力結果は次のとおりです.
{
~#"nameJson": "Leego",
~#"  ": true
~}