Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of custom unmarshal of JSON in golang
package main
import (
"encoding/json"
"fmt"
"reflect"
)
type To []string
type Message struct {
From string `"json:from"`
To To `"json:to"`
Message string `"json:message"`
}
func (c *To) UnmarshalJSON(data []byte) error {
var nums interface{}
err := json.Unmarshal(data, &nums)
if err != nil {
return err
}
items := reflect.ValueOf(nums)
switch items.Kind() {
case reflect.String:
*c = append(*c, items.String())
case reflect.Slice:
*c = make(Contacts, 0, items.Len())
for i := 0; i < items.Len(); i++ {
item := items.Index(i)
switch item.Kind() {
case reflect.String:
*c = append(*c, item.String())
case reflect.Interface:
*c = append(*c, item.Interface().(string))
}
}
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.