Hi,
I have been struggling with an issue with the usage of int64 inside a struct. When parsing into Json in Go and from the 17th digits onwards I have noticed that it starts round the int64 up. For example: 2882795323592627689 => 2882795323592627700
My understanding is that json "numbers" get treated as floating points and therefore they are limited to 53 digits of integer precision. I cannot change my original struct and from the client point of view I still need to have a int64 and it is imperative to have it the same as it identifies a specific request. Can you help with this?
What I have tried:
This is my current implementation:
Function to convert
[]bytes
to
int64
:
func convertToInt64(raw []byte) int64 {
buffer := bytes.NewBuffer(raw)
var v int64
err := binary.Read(buffer, binary.LittleEndian, &v)
if err != nil {
}
return v
}
This, in turns, is used inside a function that construct the struct mapping and does the Json unmarshalling:
func retrieveStructMap(value interface{}) interface{} {
var data []byte
switch v := value.(type) {
case map[string]interface{}:
return v
case int64:
v = bytesToInt64(data)
default:
}
if data != nil {
structMap := make(map[string]interface{})
err := json.Unmarshal(data, &structMap)
if err == nil {
return structMap
}
}
return map[string]interface{}{
"key": value,
}
}
I have consulted various resources, but with no joy as my main issue seems to be to be able to treat "in a special way" only the int64 in the struct:
https://stackoverflow.com/questions/16946306/preserve-int64-values-when-parsing-json-in-go
https://github.com/golang/go/issues/5562
https://play.golang.org/p/gHEj8WHuTx
Any idea, can you help? The issue I have is that this needs being rather generic for a multiple of fields one of which unfortunately is int64 and exceeds 17 digits, therefore the situation is complicated by the usage of the generic
interface{}
I have attempted at using my own
json.Number
field in a custom struct, but I cannot make it generic enough
Thank you