Created
September 23, 2014 02:20
-
-
Save jessejlt/04a1a3ff0cd79a4b8284 to your computer and use it in GitHub Desktop.
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
package main | |
import ( | |
"encoding" | |
"encoding/json" | |
"fmt" | |
) | |
func main() { | |
var str string | |
if err := unmarshaler(&str); nil != err { | |
fmt.Println(err) | |
return | |
} | |
fmt.Printf("str=%s\n", str) | |
si := &simple{} | |
if err := unmarshaler(si); nil != err { | |
fmt.Println(err) | |
return | |
} | |
fmt.Printf("simple=%+v\n", si) | |
b := []byte{} | |
if err := unmarshaler(&b); nil != err { | |
fmt.Println(err) | |
return | |
} | |
fmt.Printf("b=%s\n", b) | |
} | |
type simple struct { | |
A string `json:"a"` | |
B string `json:"b"` | |
} | |
func unmarshaler(value interface{}) error { | |
var err error | |
data := `{"a":"beep","b":"boop"}` | |
switch value := value.(type) { | |
case nil: | |
case *string: | |
fmt.Println("*string") | |
*value = data | |
case *[]byte: | |
fmt.Println("*[]byte") | |
*value = []byte(data) | |
case encoding.TextUnmarshaler: | |
fmt.Println("encoding.TextUnmarshaler") | |
err = value.UnmarshalText([]byte(data)) | |
default: | |
fmt.Println("default") | |
err = json.Unmarshal([]byte(data), value) | |
} | |
return err | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment