Last active
August 29, 2015 14:27
-
-
Save porfirion/f9a8c5d3a7560f73dc74 to your computer and use it in GitHub Desktop.
golang fails to parse json for object, created by reflection
This file contains 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/json" | |
"fmt" | |
"reflect" | |
) | |
type Message struct { | |
Data string | |
} | |
func main() { | |
source := Message{Data: "hello world"} | |
fmt.Printf("Source message: %#v\n\n", source) // Source message: main.Message{Data:"hello world"} | |
data, err := json.Marshal(source) | |
var destination1 Message | |
var destination2 Message = reflect.Zero(reflect.TypeOf(Message{})).Interface().(Message) | |
var destination3 interface{} = reflect.Zero(reflect.TypeOf(Message{})).Interface() | |
fmt.Printf("Destination1 value: %#v\n", destination1) // Destination1 value: main.Message{Data:""} | |
fmt.Printf("Destination2 value: %#v\n", destination2) // Destination1 value: main.Message{Data:""} | |
fmt.Printf("Destination3 value: %#v\n", destination3) // Destination1 value: main.Message{Data:""} | |
fmt.Println() | |
err = json.Unmarshal(data, &destination1) | |
err = json.Unmarshal(data, &destination2) | |
err = json.Unmarshal(data, &destination3) | |
fmt.Printf("Destination1: %#v Error: %v\n", destination1, err) // Destination1: main.Message{Data:"hello world"} Error: <nil> | |
fmt.Printf("Destination2: %#v Error: %v\n", destination2, err) // Destination2: main.Message{Data:"hello world"} Error: <nil> | |
fmt.Printf("Destination3: %#v Error: %v\n", destination3, err) // Destination3: map[string]interface {}{"Data":"hello world"} Error: <nil> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://play.golang.org/p/QEyDN9vztr