2015-05-09 67 views
1

當我嘗試整理一下地圖,json.Marshal回報:json.Marshal地圖JSON陣列

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

這是正常現象。但我可以名帥這:

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

回答

1

您可以自定義一個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