Created
July 19, 2022 03:46
-
-
Save satorunooshie/ab4dc4e00bcb1d2350b355fba9a6d49f to your computer and use it in GitHub Desktop.
App Store Server Notifications V2でドキュメントに存在しないフィールドを保存する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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