package main
import (
"encoding/json"
"fmt"
)
type Bird struct {
A map[string]string `json:"a"`
}
func (bd *Bird) MarshalJSON() ([]byte, error) {
// 注意:此处不能使用Bird类型的变量,否则会陷入死循环
l := []string{}
for _,v := range bd.A {
l = append(l,v)
}
return json.Marshal(l)
}
func (bd *Bird) UnmarshalJSON(b []byte) error {
// 注意:此处不能使用Bird类型的变量,否则会陷入死循环
l := []string{}
err := json.Unmarshal(b, &l)
if err != nil {
return err
}
for i,v := range l {
k := fmt.Sprintf("%d", i)
bd.A[k] = v
}
return nil
}
func main() {
m := map[string]string{"1": "110", "2":"120", "3":"119"}
xiQue := &Bird{A:m}
xJson, err := json.Marshal(xiQue)
if err != nil {
fmt.Println("json.Marshal failed:", err)
}
fmt.Println("xJson:", string(xJson))
b := `["apple", "orange", "banana"]`
baoXiNiao := &Bird{A:map[string]string{}}
//json.Unmarshal的第二个参数只有为Bird类型时才会调用自己实现的接口
err = json.Unmarshal([]byte(b), baoXiNiao)
if err != nil {
fmt.Println("json.Unmarshal failed:", err)
}
fmt.Println("baoXiNiao:", baoXiNiao)
}
xJson: [“110”,“120”,“119”]
baoXiNiao: &{map[0:apple 1:orange 2:banana]}