I have problem when Unmarshal json string into struct that is the numeric value with exponent will alway be 0. Please check code below :
package main
import (
"encoding/json"
"fmt"
"os"
)
type Person struct {
Id uint64 `json:"id"`
Name string `json:"name"`
}
func main() {
//Create the Json string
var b = []byte(`{"id": 1.2E+8, "Name": "Fernando"}`)
//Marshal the json to a proper struct
var f Person
json.Unmarshal(b, &f)
//print the person
fmt.Println(f)
//unmarshal the struct to json
result, _ := json.Marshal(f)
//print the json
os.Stdout.Write(result)
}
And the run is :
{0 Fernando}
Is there any way to make it work? Since the exponent thing is standart JSON. It seems the golang wrong interpret it.
Here the playground : http://play.golang.org/p/8owgjX9y0m
Change the Id
type from int64
to float32
or float64
.
http://play.golang.org/p/-zidTD_q8y
EDIT: This may be a bit of a hack, but you can add a "dummy" Id
field of type float64
and write a hook to cast the value to the actual Id
type int64
.
type Person struct {
Id float64 `json:"id"`
_Id int64
Name string `json:"name"`
}
var f Person
var b = []byte(`{"id": 1.2e+8, "Name": "Fernando"}`)
_ = json.Unmarshal(b, &f)
if reflect.TypeOf(f._Id) == reflect.TypeOf((int64)(0)) {
fmt.Println(f.Id)
f._Id = int64(f.Id)
}
just change the type of id field into float64.
package main
import (
"encoding/json"
"fmt"
"os"
)
type Person struct {
Id float64 `json:"id"`
Name string `json:"name"`
}
func main() {
//Create the Json string
var b = []byte(`{"id": 1.2E+8, "Name": "Fernando"}`)
//Marshal the json to a proper struct
var f Person
json.Unmarshal(b, &f)
//print the person
fmt.Println(f)
//unmarshal the struct to json
result, _ := json.Marshal(f)
//print the json
os.Stdout.Write(result)
}