#Struct with a Generic and Json Unmarshalling

2 messages · Page 1 of 1 (latest)

untold whale
#

Trying something a little silly here and wondering if there some clever workaround to it:
If I have a struct defined as

type response[T any] struct {
  Data []T
  Meta Meta `json:"meta"`
}

And I wanted to define another type as:

type Things response[Thing]

I might have a response from an API that sends me back data like this:

{
  "things": ...
  "meta": ...
}

when I go to fetch from it. However, if I wanted data like:

type AnotherThings response[AnotherThing]

The data from the API would come back like this:

{
  "another_things": ...
  "meta": ...
}

The issue being, when I try to unmarshal the byte response into a Things type, the lack of a tag means it can't map to Thing because the response struct has it named as Data
Is there any workaround here I could get to somehow dynamically declare the tag? My research indicates a no, but its a fairly specific topic so I haven't turned up a lot of results of people trying similar things.
I'm not married to doing it this way since I could easily just ditch the generic response struct and declare structs like

type Things struct {
  Data []Thing `json:"thing"`
  Meta Meta `json:"meta"`
}

But I'm curious enough to ask!

slender spade
#

you need implement your custom JSON unmarshal method for that.
In the unmarshal method, you can firstly decode it into a map, then check the key.
You can get the key from type's name by using reflect