Skip to content

Instantly share code, notes, and snippets.

@kkdai
Forked from twsiyuan/Go-MarshalJSON-Problem.go
Created August 10, 2016 06:10
Show Gist options
  • Save kkdai/08430ae177c60d272acfd0ee8e7d210c to your computer and use it in GitHub Desktop.
Save kkdai/08430ae177c60d272acfd0ee8e7d210c to your computer and use it in GitHub Desktop.
詢問用範例
package math
type A struct {
FieldA1 int32
FieldA2 int32
}
func (this A) MarshalJSON() ([]byte, error) {
m := make(map[string]interface{}, 3)
m["FieldA1"] = this.FieldA1
m["FieldA2"] = this.FieldA2
m["FieldATotal"] = this.FieldA1 + this.FieldA2
return json.Marshal(m)
}
type B strcut{
A
FieldB1 int32
FieldB2 int32
}
func (this B) MarshalJSON() ([]byte, error) {
m := make(map[string]interface{}, 3)
// 有沒有更優雅的做法?More elegant
m["FieldA1"] = this.A.FieldA1
m["FieldA2"] = this.A.FieldA2
m["FieldATotal"] = this.A.FieldA1 + this.A.FieldA2
m["FieldBTotal"] = this.FieldB1 + this.FieldB2
return json.Marshal(m)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment