json.Marshal映射到JSON数组

时间:2021-11-15 19:35:35

When i try Marshal a map, json.Marshal return:

当我尝试Marshal一张地图时,json.Marshal回归:

{"Map Key":"Map Value"}...

This is normal behavior. But i can marshal this to:

这是正常行为。但我可以将其编组为:

{"Map":[{"Name":"Map Key","Date":"Map Value"},{"Name":"Map Key2","Date":"Map Value2"}]}

1 个解决方案

#1


You can define a custom json.Marshaler interface to do that, for example:

您可以定义自定义的json.Marshaler接口来执行此操作,例如:

type mapInfo struct {
    Name string `json:"name"`
    Date string `json:"date"`
}

type CustomMap map[string]string

func (cm CustomMap) MarshalJSON() ([]byte, error) {
    // if you want to optimize you can use a bytes.Buffer and write the strings out yourself.
    var out struct {
        Map []mapInfo `json:"map"`
    }
    for k, v := range cm {
        out.Map = append(out.Map, mapInfo{k, v})
    }
    return json.Marshal(out)
}

func (cm CustomMap) UnmarshalJSON(b []byte) (err error) {
    var out struct {
        Map []mapInfo `json:"map"`
    }
    if err = json.Unmarshal(b, &out); err != nil {
        return
    }
    for _, v := range out.Map {
        cm[v.Name] = v.Date
    }
    return
}

playground

#1


You can define a custom json.Marshaler interface to do that, for example:

您可以定义自定义的json.Marshaler接口来执行此操作,例如:

type mapInfo struct {
    Name string `json:"name"`
    Date string `json:"date"`
}

type CustomMap map[string]string

func (cm CustomMap) MarshalJSON() ([]byte, error) {
    // if you want to optimize you can use a bytes.Buffer and write the strings out yourself.
    var out struct {
        Map []mapInfo `json:"map"`
    }
    for k, v := range cm {
        out.Map = append(out.Map, mapInfo{k, v})
    }
    return json.Marshal(out)
}

func (cm CustomMap) UnmarshalJSON(b []byte) (err error) {
    var out struct {
        Map []mapInfo `json:"map"`
    }
    if err = json.Unmarshal(b, &out); err != nil {
        return
    }
    for _, v := range out.Map {
        cm[v.Name] = v.Date
    }
    return
}

playground