Golang Json Unmarshal Numeric with Exponent
When unmarshaling a JSON string into a struct in Golang, numeric values with exponents are often interpreted as 0. This can be a challenge, as exponents are a standard part of the JSON specification.
To address this issue, the type of the numeric field must be modified to either float32 or float64. These floating-point types support the representation of exponents. For example:
type Person struct { Id float64 `json:"id"` _Id int64 Name string `json:"name"` }
After changing the type, unmarshaling the JSON string into the struct will correctly parse the numeric value with the exponent.
Alternative Approach with a Helper Function
If you require the numeric field to be an integer, you can use a helper function to cast the floating-point value to the integer type after unmarshaling:
import ( "encoding/json" "fmt" "math" "os" "reflect" ) 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"}`) func main() { _ = json.Unmarshal(b, &f) if reflect.TypeOf(f._Id) == reflect.TypeOf((int64)(0)) { fmt.Println(math.Trunc(f.Id)) f._Id = int64(f.Id) } }
In this example, the helper function math.Trunc truncates the floating-point value to an integer. The truncated value is then assigned to the _Id field.
以上がGolang で指数を使用して JSON 数値をアンマーシャリングする方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。