Skip to content

Instantly share code, notes, and snippets.

@erans
Created July 18, 2016 07:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erans/4038d3c9bbc0b25a8a48e27010d92eb7 to your computer and use it in GitHub Desktop.
Save erans/4038d3c9bbc0b25a8a48e27010d92eb7 to your computer and use it in GitHub Desktop.
Unmarshaling JSON text with a long integer number to Struct with field of type interface{}
package main
import (
"encoding/json"
"fmt"
)
type container struct {
Name string
Value interface{}
}
type person struct {
Name string
Number uint64
}
func main() {
// Raw data
data := "{\"Name\":\"Container\",\"Value\":{\"Name\":\"Joe\",\"Number\":123456789}}"
c := &container{}
// After unmarshaling "Number" will be 1.23456789e+08 instead of 123456789
// As the default Unmarshaling logic is to use float64
json.Unmarshal([]byte(data), c)
fmt.Printf("%v\n", c)
// At this point Value was marshaled into a generic map map[string]interface{}.
// Therefore, we cannot cast c.Value into a struct of type person.
// To do that we can Marshal c.Value and unmarshal it into a person struct,
// however, this will cause an error because the value of "Number" is float
// and not an integer
marshaledValue, _ := json.Marshal(c.Value)
p := &person{}
if err := json.Unmarshal(marshaledValue, p); err != nil {
fmt.Printf("%v\n", err)
return
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment