package mainimport ("encoding/json""fmt""log""strings"
)type Structs struct {Name string `json:"name"`Gender int `json:"gender"`
}// MarshalJSON 重写序列化方法,如果gender是0则改为woman,如果是1则改为man
func (s Structs) MarshalJSON() ([]byte, error) {var genderStr stringswitch s.Gender {case 0:genderStr = "woman"case 1:genderStr = "man"default:genderStr = "unknown"}type Alias Structsreturn json.Marshal(&struct {AliasGender string `json:"gender"`}{Alias: Alias(s),Gender: genderStr,})
}// UnmarshalJSON 重写反序列化方法,如果gender是man,则改为1,如果为woman改为0
func (s *Structs) UnmarshalJSON(data []byte) error {type Alias Structsaux := struct {Gender string `json:"gender"`*Alias}{Alias: (*Alias)(s),}if err := json.Unmarshal(data, &aux); err != nil {return err}switch strings.ToLower(aux.Gender) {case "woman":s.Gender = 0case "man":s.Gender = 1default:return fmt.Errorf("invalid gender value: %s", aux.Gender)}return nil
}func marshalJSON() {gg := Structs{Name: "gg",Gender: 1,}mm := Structs{Name: "mm",Gender: 0,}ggdata, err := json.Marshal(gg)if err != nil {log.Fatalln(err)}fmt.Printf("ggdata: %v\n", string(ggdata))mmdata, err := json.Marshal(mm)if err != nil {log.Fatalln(err)}fmt.Printf("mmdata: %v\n", string(mmdata))// Output:// ggdata: {"name":"gg","gender":"man"}// mmdata: {"name":"mm","gender":"woman"}
}func unmarshalJSON() {ggdata := `{"name":"gg","gender":"man"}`var gg Structsif err := json.Unmarshal([]byte(ggdata), &gg); err != nil {log.Fatalln(err)}fmt.Printf("%#v\n", gg)mmdata := `{"name":"mm","gender":"woman"}`var mm = Structs{}if err := json.Unmarshal([]byte(mmdata), &mm); err != nil {log.Fatalln(err)}fmt.Printf("%#v\n", mm)// Output:// main_test.Structs{Name:"gg", Gender:1}// main_test.Structs{Name:"mm", Gender:0}
}func main() {marshalJSON()fmt.Println(strings.Repeat("=", 30))unmarshalJSON()
}