Unmarshaling nested JSON objects

后端 未结 8 1707
轻奢々
轻奢々 2020-11-27 11:37

There are a few questions on the topic but none of them seem to cover my case, thus I\'m creating a new one.

I have JSON like the following:

{\"foo\"         


        
相关标签:
8条回答
  • 2020-11-27 11:56

    Is there a way to unmarshal the nested bar property and assign it directly to a struct property without creating a nested struct?

    No, encoding/json cannot do the trick with ">some>deep>childnode" like encoding/xml can do. Nested structs is the way to go.

    0 讨论(0)
  • 2020-11-27 12:05

    Like what Volker mentioned, nested structs is the way to go. But if you really do not want nested structs, you can override the UnmarshalJSON func.

    https://play.golang.org/p/dqn5UdqFfJt

    type A struct {
        FooBar string // takes foo.bar
        FooBaz string // takes foo.baz
        More   string 
    }
    
    func (a *A) UnmarshalJSON(b []byte) error {
    
        var f interface{}
        json.Unmarshal(b, &f)
    
        m := f.(map[string]interface{})
    
        foomap := m["foo"]
        v := foomap.(map[string]interface{})
    
        a.FooBar = v["bar"].(string)
        a.FooBaz = v["baz"].(string)
        a.More = m["more"].(string)
    
        return nil
    }
    

    Please ignore the fact that I'm not returning a proper error. I left that out for simplicity.

    UPDATE: Correctly retrieving "more" value.

    0 讨论(0)
提交回复
热议问题