亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

帶有長數字的 JSON 解組給出浮點數

帶有長數字的 JSON 解組給出浮點數

Go
鳳凰求蠱 2021-07-27 17:57:28
例如,我正在使用 golang 對 JSON 進行編組和解組,當我想對數字字段進行處理時,golang 會將其轉換為浮點數而不是長數字。我有以下 JSON:{    "id": 12423434,     "Name": "Fernando"}在marshal它到地圖并unmarshal再次到 json 字符串之后,我得到:{    "id":1.2423434e+07,    "Name":"Fernando"}如您所見,該"id"字段采用浮點表示法。我正在使用的代碼如下:package mainimport (    "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。我怎樣才能把它修好?這是goland playground中程序的鏈接:http ://play.golang.org/p/RRJ6uU4Uw-
查看完整描述

2 回答

?
12345678_0001

TA貢獻1802條經驗 獲得超5個贊

有時您無法提前定義結構,但仍然需要數字不變地通過 marshal-unmarshal 過程。


在這種情況下,您可以使用UseNumberon 方法json.Decoder,這會導致所有數字解組為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}


查看完整回答
反對 回復 2021-08-02
  • 2 回答
  • 0 關注
  • 299 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號