Unmarshalling multi-type json field into struct for use with xorm

First-time poster here, and I desperately need help.
I have an API that my code is getting responses from and a few fields are not strongly typed and I need to figure out a way to unmarshal those in a manner that makes them usable by xorm.

example: https://play.golang.org/p/5_b-ihLJhkK

As you can see the colors field in the json can either be of type string or type []string when it comes to marshaling into the struct.
Clearly, this can’t be done in a straight forward fashion and so an interface must be used to allow for the non-type-safe field.
However, xorm (understandably) can’t translate an empty interface to a column type nor can it do so with json.RawMessage and make the data meaningful.

Sadly I don’t have control over the API and how it returns the response or this would be very simple.

Does anyone here know of a way that you can define the type post unmarshaling and still keep it within a usable format for DB insertion?

Any help would be incredibly appreciated as I’ve been banging my head on this problem for a while now.

Thanks in advance,

2 Likes

Why don’t you use one struct for JSON decoding and another (more strictly typed) for database insertion? Then you can assign values from one to another and also assert and comvert types.

2 Likes

I didn’t want to use two structs which so closely resemble each others as I don’t like repeating code when I don’t have to, and also the structs that I’m actually working with a fairly large (the ones in the example are just dummy responses and which loosely resemble the type of response I’m working with). Additionally there’s always a chance that some later developer might have a difficult time following along with that.

I think I did find a solution however, well a couple. Utilizing the UnmarshalJSON method.
Here’s the example : https://play.golang.org/p/balvVjx85Jv

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.