Skip to content

Instantly share code, notes, and snippets.

@satorunooshie
Created July 19, 2022 03:46
Show Gist options
  • Select an option

  • Save satorunooshie/ab4dc4e00bcb1d2350b355fba9a6d49f to your computer and use it in GitHub Desktop.

Select an option

Save satorunooshie/ab4dc4e00bcb1d2350b355fba9a6d49f to your computer and use it in GitHub Desktop.
App Store Server Notifications V2でドキュメントに存在しないフィールドを保存する
type Payload struct {
// 省略.
Type *string `json:"type"`
WebOrderLineItemID *string `json:"webOrderLineItemId"`
Unknown map[string]json.RawMessage `json:"-"`
}
// NOTE: omitempty など json tag を追加する場合は修正が必要.
func (r *Payload) UnmarshalJSON(b []byte) error {
rv := reflect.ValueOf(r).Elem()
knownFields := map[string]reflect.Value{}
for i := 0; i != rv.NumField(); i++ {
jsonName := rv.Type().Field(i).Tag.Get("json")
knownFields[jsonName] = rv.Field(i)
}
if err := json.Unmarshal(b, &r.Unknown); err != nil {
return err
}
for key, chunk := range r.Unknown {
if field, found := knownFields[key]; found {
if err := json.Unmarshal(chunk, field.Addr().Interface()); err != nil {
return err
}
delete(r.Unknown, key)
}
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment