这很麻烦,但是如果您可以将该结构包装在另一个结构中,并使用新的结构进行编码,则可以:
- 编码原始结构,
- 解码为
interface{}以获得地图 - 更换地图钥匙
- 然后对地图进行编码并返回
从而:
type MyUser struct { U User}func (u MyUser) MarshalJSON() ([]byte, error) { // enpre the original m, _ := json.Marshal(u.U) // depre it back to get a map var a interface{} json.Unmarshal(m, &a) b := a.(map[string]interface{}) // Replace the map key b["name"] = b["first"] delete(b, "first") // Return encoding of the map return json.Marshal(b)}在操场上:https :
//play.golang.org/p/TabSga4i17



