JSON unmarshaling with long numbers gives floating point number

后端 未结 2 1477
栀梦
栀梦 2020-12-24 01:40

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,

2条回答
  •  春和景丽
    2020-12-24 02:39

    There are times when you cannot define a struct in advance but still require numbers to pass through the marshal-unmarshal process unchanged.

    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.

    For example:

    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)
    }
    

    Result:

    decoded to map[string]interface {}{"id":"12423434", "Name":"Fernando"}
    encoded to {"Name":"Fernando","id":12423434}
    

提交回复
热议问题