带有长数字的JSON解组可提供浮点数 [英] JSON unmarshaling with long numbers gives floating point number
问题描述
我正在使用golang编组和解组JSON,例如,当我想对数字字段进行编组时,golang会将其转换为浮点数而不是使用长数.
I was marshaling and unmarshaling JSONs using golang and when I want to do it with number fields golang transforms it in floating point numbers instead of use long numbers, for example.
我有以下JSON:
{
"id": 12423434,
"Name": "Fernando"
}
在marshal
之后将其映射到地图,然后将unmarshal
再次转换为json字符串:
After marshal
it to a map and unmarshal
again to a json string I get:
{
"id":1.2423434e+07,
"Name":"Fernando"
}
如您所见,"id"
字段采用浮点表示法.
As you can see the "id"
field is in floating point notation.
我正在使用的代码如下:
The code that I am using is the following:
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}
似乎是地图的第一个marshal
生成了FP.我该如何解决呢?
It appears to be that the first marshal
to the map generates the FP. How can I fix it to a long?
这是goland游乐场中程序的链接: http://play.golang.org/p/RRJ6uU4Uw-
This is the link to the program in the goland playground: http://play.golang.org/p/RRJ6uU4Uw-
推荐答案
有时您无法预先定义结构,但仍要求数字不变地通过编组-解组过程.
There are times when you cannot define a struct in advance but still require numbers to pass through the marshal-unmarshal process unchanged.
在这种情况下,您可以在json.Decoder
上使用UseNumber
方法,这将导致所有数字都以json.Number
的形式编组(这只是数字的原始字符串表示形式).这对于在JSON中存储很大的整数也很有用.
In that case you can use the UseNumber
method on json.Decoder
, which causes all numbers to unmarshal as json.Number
(which is just the original string representation of the number). This can also useful for storing very big integers in 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解组可提供浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!