Golang encoding/json
package lets you use ,string
struct tag in order to marshal/unmarshal string values (like "309230"
) into int64
field. Example:
Int64String int64 `json:",string"`
However, this doesn't work for slices, ie. []int64
:
Int64Slice []int64 `json:",string"` // Doesn't work.
Is there any way to marshal/unmarshal JSON string arrays into []int64 field?
Quote from https://golang.org/pkg/encoding/json:
The "string" option signals that a field is stored as JSON inside a JSON-encoded string. It applies only to fields of string, floating point, integer, or boolean types. This extra level of encoding is sometimes used when communicating with JavaScript programs:
Best Answer
For anyone interested, I found a solution using a custom type having
MarshalJSON()
andUnmarshalJSON()
methods defined.The above solution marshals
[]int64
into JSON string array. Unmarshaling works from both JSON string and integer arrays, ie.:See example at https://play.golang.org/p/BOqUBGR3DXm