将`json.Marshal`函数用于将`map`转换为JSON数组。

huangapple go评论70阅读模式
英文:

json.Marshal map to JSON array

问题

当我尝试序列化一个map时,json.Marshal返回:

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

这是正常的行为。但是我可以将其序列化为:

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

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

{"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

得分: 2

你可以定义一个自定义的json.Marshaler接口来实现这个功能,例如:

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

type CustomMap map[string]string

func (cm CustomMap) MarshalJSON() ([]byte, error) {
    // 如果你想要优化,可以使用bytes.Buffer并自己写入字符串。
    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
}

[kbd]playground/kbd

英文:

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

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
}

<kbd>playground</kbd>

huangapple
  • 本文由 发表于 2015年5月9日 08:50:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/30134828.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定