Reputation: 7466
When you unmarshal JSON to []interface{}
is there any way to automatically detect the type besides some standard types like bool, int and string?
What I noticed is the following, Let's say I marshal [uuid.UUID, bool]
then the JSON I get looks like:
[[234,50,7,116,194,41,64,225,177,151,60,195,60,45,123,106],true]
When I unmarshal it again, I get the types as shown through reflect
:
[]interface{}, bool
I don't understand why it picked []interface{}
. If it cannot detect it, shouldn't it be at least interface{}
?
In any case, my question is, is it possible to unmarshal any type when the target is of type []interface{}
? It seems to work for standard types like string, bool, int but for custom types I don't think that's possible, is it? You can define custom JSON marshal/unmarshal methods but that only works if you decode it into a target type so that it can look up which custom marshal/unmarshal methods to use.
Upvotes: 1
Views: 425
Reputation: 417702
You can unmarshal any type into a value of type interface{}
. If you use a value of type []interface{}
, you can only unmarshal JSON arrays into it, but yes, the elements of the array may be of any type.
Since you're using interface{}
or []interface{}
, yes, type information is not available, and it's up to the encoding/json
package to choose the best it sees fit. For example, for JSON objects it will choose map[string]interface{}
. The full list of default types is documented in json.Unmarshal()
:
To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:
bool, for JSON booleans float64, for JSON numbers string, for JSON strings []interface{}, for JSON arrays map[string]interface{}, for JSON objects nil for JSON null
Obviously if your JSON marshaling/unmarshaling logic needs some pre- / postprocessing, the json
package will not miraculously find it out. It can know about those only if you unmarshal into values of specific types (which implement json.Unmarshaler
). The json
package will still be able to unmarshal them to the default types, but custom logic will obviously not run on them.
Upvotes: 3