Hello Sarah, I managed to run something implementing json.Unmarshaler : see code on playground <https://play.golang.org/p/ZMJELAZD-Y>
There are probably better/cleaner ways of doing that, suggestions welcome. Please note : - the pointer receiver (a *Address) - the local type AddressGhost, just to avoid infinite recursion json.Unmarshal -> (*Address).UnmarshalJSON -> json.Unmarshal -> ... It is common to have a "constructor" func NewAddress() *Address, but I didn't need to use one here. Also, I learnt today that you can get similar results by setting your default value before <https://play.golang.org/p/ZMJELAZD-Y> or after <https://play.golang.org/p/l7aCbuwB3h> unmarshaling. Cheers Val On Monday, October 3, 2016 at 6:39:08 AM UTC+2, Sarah Ahmed wrote: > > Hello, > I am trying to initialize the "State" to a default value "NY" of Address > slice. > The following code only sets the first element's State. > I do not know how many element would be in my input. > Is there any easy way to do it? > Thanks in advance for your help. > > package main > > import ( > "encoding/json" > "fmt" > "log" > ) > > > type Address struct { > Street string `json:"Street"` > City string `json:"City"` > State string `json:"State"` > } > > > type Person struct { > Name string `json:"Name"` > Adr []Address `json:"Address"` > } > > > var p = &Person{Adr: []Address{Address{State: "NY"}}} > > > func main() { > input:= "{\"Name\": \"User1\",\"Address\":[{\"Street\": \"Main > St\",\"City\": \"City One\"},{\"Street\": \"Central St\",\"City\": \"City > Two\"}]}" > err := json.Unmarshal([]byte(input), &p) > if err != nil { > log.Printf("Unmarshal error: ", err.Error()) > } > fmt.Printf("%#v", p) > } > > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. For more options, visit https://groups.google.com/d/optout.
