When unmarshaling JSON data into a Go structure, numeric values with exponents are often misinterpreted as zero. This occurs when the target field in the structure is declared as an integer type.
To address this issue, follow these steps:
type Person struct { Id float32 `json:"id"` Name string `json:"name"` }
Here is an example:
package main import ( "encoding/json" "fmt" "os" ) type Person struct { Id float32 `json:"id"` Name string `json:"name"` } func main() { // Create the JSON string. var b = []byte(`{"id": 1.2E+8, "Name": "Fernando"}`) // Unmarshal 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) }
This will output:
{1.2e+08 Fernando} {"id":1.2e+08,"Name":"Fernando"}
Alternative Approach:
If you must use an integer type for the field, you can employ a "dummy" field of type float64 to capture the numeric value with exponent. Then, use a hook to cast the value to the actual integer type.
Here is an example:
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) }
This will output:
1.2e+08 {Name:Fernando Id:120000000}
The above is the detailed content of How to Handle JSON Numerals with Exponents in Go?. For more information, please follow other related articles on the PHP Chinese website!