Created
May 14, 2020 13:03
-
-
Save luizvnasc/d79a5ccfd933fc0af732dc6d288cbce8 to your computer and use it in GitHub Desktop.
Unmarshal de interface{}
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/xml" | |
"fmt" | |
) | |
type Person struct { | |
XMLName xml.Name `xml:"person"` | |
FirstName string `xml:"firstname"` | |
Parents interface{} `xml:"parent"` | |
} | |
func (p *Person) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { | |
type person struct { | |
XMLName xml.Name `xml:"person"` | |
FirstName string `xml:"firstname"` | |
Parents intf `xml:"parent"` | |
} | |
var pp person | |
pp.Parents = intf{p.Parents} | |
if err := d.DecodeElement(&pp, &start); err != nil { | |
return err | |
} | |
p.FirstName = pp.FirstName | |
return nil | |
} | |
type intf struct { | |
value interface{} | |
} | |
func (i intf) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { | |
return d.DecodeElement(i.value, &start) | |
} | |
func main() { | |
type Parent struct { | |
FirstName string `xml:"name"` | |
LastName string `xml:"lastname"` | |
} | |
var p Person | |
p.FirstName = "Steve" | |
p.Parents = []Parent{{"Jack", "Doe"}, {"Lynne", "Doe"}} | |
data, err := xml.Marshal(p) | |
if err != nil { | |
fmt.Println(err) | |
} | |
fmt.Println("Marshalled:", string(data)) | |
var p2 Person | |
p2.Parents = new([]Parent) | |
err = xml.Unmarshal(data, &p2) | |
if err != nil { | |
fmt.Println(err) | |
} | |
fmt.Printf("Unmarshalled: %s\n", p2) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment