Quantcast
Viewing all articles
Browse latest Browse all 3

Answer by kenjoe41 for Unmarshal JSON in JSON in Go

if i were to create a custom UnmarshalJson for that data, I would create an auxiliary struct auxMain that has the same fields as the main struct but with Bar field as string. Then it unmarshals the JSON data into this auxiliary struct, extracting the Foo field and the Bar field as a string. After that, it unmarshals the Bar field as string into the Child struct, and assigns the extracted Foo field and the Child struct to the Main struct.

It's a round about way but seems to work in the playground.

func (m *Main) UnmarshalJSON(b []byte) error {    type auxMain struct {        Foo int    `json:"foo"`        Bar string `json:"bar"`    }    var a auxMain    if err := json.Unmarshal(b, &a); err != nil {        return err    }    var child Child    if err := json.Unmarshal([]byte(a.Bar), &child); err != nil {        return err    }    m.Foo = a.Foo    m.Bar = child    return nil}

try it out in the PlayGround and see: https://go.dev/play/p/wWIceUxu1tj

Don't know if this is what you are looking for.


Viewing all articles
Browse latest Browse all 3

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>