package main
import (
"encoding/json"
"fmt"
)
var bodyA = []byte(`{
"type": "A",
"data": { "name": "Johnny" }
}`)
var bodyB = []byte(`{
"type": "B",
"data": { "nickname": "J." }
}`)
type TypeA struct {
Name string `json:"name"`
}
type TypeB struct {
Nickname string `json:"nickname"`
}
func main() {
req := struct {
Type string `json:"type"`
Data any `json:"data"`
}{}
err := json.Unmarshal(bodyA, &req) // bodyB
if err != nil {
panic(err)
}
switch req.Type {
case "A":
req.Data = new(TypeA)
case "B":
req.Data = new(TypeB)
}
err = json.Unmarshal(bodyA, &req) // bodyB
if err != nil {
panic(err)
}
message, _ := json.Marshal(&req)
fmt.Println(string(message))
}
Unmarshal dynamic JSON based on a type key
https://play.golang.com/p/BPWVd0WAfqR