例如,我使用 golang 编码和解码 JSON,当我想用数字字段进行编码时,golang 将其转换为 float 而不是使用长数字。
我有以下 JSON:
{
"id": 12423434,
"Name": "Fernando"
}
在 marshal
到 map 并再次unmarshal
到 json 字符串后,我得到:
{
"id":1.2423434e+07,
"Name":"Fernando"
}
如您所见,“id”
字段采用浮点表示法。
我使用的代码如下:
package main
import (
"encoding/json"
"fmt"
"os"
)
func main() {
//Create the Json string
var b = []byte(`
{
"id": 12423434,
"Name": "Fernando"
}
`)
//Marshal the json to a map
var f interface{}
json.Unmarshal(b, &f)
m := f.(map[string]interface{})
//print the map
fmt.Println(m)
//unmarshal the map to json
result,_:= json.Marshal(m)
//print the json
os.Stdout.Write(result)
}
它打印:
map[id:1.2423434e+07 Name:Fernando]
{"Name":"Fernando","id":1.2423434e+07}
似乎是 map 的第一个 marshal
生成了 FP。我怎样才能把它修长?
这是 goland playground 中程序的链接: http://play.golang.org/p/RRJ6uU4Uw-
最佳答案
有时您无法提前定义结构,但仍需要数字不变地通过编码-解码过程。
在这种情况下,您可以在 json.Decoder
上使用 UseNumber
方法,这会导致所有数字解码为 json.Number
(这只是数字的原始字符串表示形式)。这对于在 JSON 中存储非常大的整数也很有用。
例如:
package main
import (
"strings"
"encoding/json"
"fmt"
"log"
)
var data = `{
"id": 12423434,
"Name": "Fernando"
}`
func main() {
d := json.NewDecoder(strings.NewReader(data))
d.UseNumber()
var x interface{}
if err := d.Decode(&x); err != nil {
log.Fatal(err)
}
fmt.Printf("decoded to %#v\n", x)
result, err := json.Marshal(x)
if err != nil {
log.Fatal(err)
}
fmt.Printf("encoded to %s\n", result)
}
结果:
decoded to map[string]interface {}{"id":"12423434", "Name":"Fernando"}
encoded to {"Name":"Fernando","id":12423434}
关于长数字的 JSON 解码给出 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56172138/