pquerna / ffjson

faster JSON serialization for Go
Apache License 2.0
2.97k stars 234 forks source link

Unmarshal interface to int64 #226

Closed xyoun closed 7 years ago

xyoun commented 7 years ago
package main

import (
    "fmt"
    "strings"
    "encoding/json"
    "github.com/pquerna/ffjson/ffjson"
)

type BigNum struct {
    Num interface{}
}

func jsonDecode(str string) {
    m := BigNum{}
    d := json.NewDecoder(strings.NewReader(str))
    d.UseNumber()
    d.Decode(&m)
    fmt.Println(m)
}

func ffjsonDecode(str string) {
    m := BigNum{}
    ffjson.Unmarshal([]byte(str), &m)
    fmt.Println(m)
}

func main() {
    str := `{"Num": 1234567890123456789}`
    jsonDecode(str)
    ffjsonDecode(str)
}

Output:

{1234567890123456789}
{1.2345678901234568e+18}

it seems that ffjson have no way to force unmarshal an interface to int64. but encoding/jjson can do it.

erikdubbelboer commented 7 years ago

ffjson doesn't have the option to unmarshal numbers into a string like encoding/json has. I would suggest not using an interface{} but instead either use int64 if you know it's a number, string if you're not sure so you can do the parsing yourself (this is exactly what encoding/json does). Or just implement a custom type that implements its own UnmarshalJSON function.