Skip to content

Instantly share code, notes, and snippets.

@porfirion
Last active August 29, 2015 14:27
Show Gist options
  • Save porfirion/f9a8c5d3a7560f73dc74 to your computer and use it in GitHub Desktop.
Save porfirion/f9a8c5d3a7560f73dc74 to your computer and use it in GitHub Desktop.
golang fails to parse json for object, created by reflection
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>
}
@porfirion
Copy link
Author

In first two cases unmarshal returns Message, but in the third case unmarshal returns map[string]interface instead of Message

@porfirion
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment