长数字的 JSON 解码给出 float

标签 json floating-point go marshalling

例如,我使用 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/

相关文章:

ajax - 在 MVC 3 中为 AJAX 请求反序列化字典时出现问题(一种开箱即用的经典 ASP.NET Webforms 方法)

json - 我可以在 JSON Schema 中设置确切的值吗?

c# - 通过Ajax方法发送文本到 Controller

ios - 从 NSString 对象返回的浮点值不是我所期望的,我该如何更正从 NSString 中提取 float ?

floating-point - Webgl 奇怪的 float 学

dictionary - 是 "bad form"在一条语句中进行map lookup和type assertion吗?

json - 如何以 POST 方法从 csv 文件发送 JSON 数据?

C: 浮点运算的结果总是归一化的吗?

go - 我正在使用 Antlr4 创建一种语言,然后我想用它生成 LLVM IR。我是否需要手写 LLVM IR 来响应我的访问者事件?

go - 如何向 Golang 中的对象发送消息? (.send() 等价于 go)