【发布时间】:2019-09-04 18:10:48
【问题描述】:
当将 json 字符串解组到结构中时,我遇到问题,即指数的数值始终为 0。 请检查以下代码:
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)
}
运行是:
{0 Fernando}
有什么方法可以让它工作吗?由于指数是标准的 JSON。看来golang的解释错了。
【问题讨论】:
-
我猜这里的问题是 Go unmarshaller 不接受用指数表示法指定的整数——解组为
float64然后转换为uint64是否可行? -
我相信这是由类型引起的问题,我感觉 OP 希望该字段为 uint64。所以正确的做法是将JSON字段类型改为
float64,然后在你想使用的时候进行类型转换为uint64。 -
是的,看来我们需要一个浮点数。但是有可能使它成为int64吗?还是我需要手动转换?