|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "encoding/xml" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "os" |
| 9 | +) |
| 10 | + |
| 11 | +type Person struct { |
| 12 | + Name string `json:"name" xml:"name"` |
| 13 | + Age int `json:"age" xml:"age"` |
| 14 | + DateBorn string `json:"date" xml:"date"` |
| 15 | + ProgramingLanguage []string `json:"languages" xml:"languages"` |
| 16 | +} |
| 17 | + |
| 18 | +func main() { |
| 19 | + // Escribir JSON |
| 20 | + p := Person{Name: "John Doe", Age: 30, DateBorn: "09-12-2023", ProgramingLanguage: []string{"go", "c", "asm"}} |
| 21 | + fileJSON, _ := os.Create("person.json") |
| 22 | + |
| 23 | + err := json.NewEncoder(fileJSON).Encode(p) |
| 24 | + if err != nil { |
| 25 | + print(err.Error()) |
| 26 | + } |
| 27 | + fileJSON.Close() |
| 28 | + // Escribir XML |
| 29 | + filexml, _ := os.Create("person.xml") |
| 30 | + |
| 31 | + encoder := xml.NewEncoder(filexml) |
| 32 | + encoder.Indent("", " ") |
| 33 | + err = encoder.Encode(p) |
| 34 | + if err != nil { |
| 35 | + print(err.Error()) |
| 36 | + } |
| 37 | + filexml.Close() |
| 38 | + jsonFile := "person.json" |
| 39 | + xmlFile := "person.xml" |
| 40 | + // Leer y decodificar JSON |
| 41 | + var personFromJson Person |
| 42 | + readAndDecode(jsonFile, &personFromJson, "json") |
| 43 | + |
| 44 | + // Leer y decodificar XML |
| 45 | + var personFromXml Person |
| 46 | + readAndDecode(xmlFile, &personFromXml, "xml") |
| 47 | + |
| 48 | + // Opcional: imprimir los datos leídos para verificación |
| 49 | + fmt.Println("Datos desde JSON:", personFromJson) |
| 50 | + fmt.Println("Datos desde XML:", personFromXml) |
| 51 | + |
| 52 | + // Eliminar archivos |
| 53 | + err = os.Remove(jsonFile) |
| 54 | + if err != nil { |
| 55 | + print(err.Error()) |
| 56 | + } |
| 57 | + err = os.Remove(xmlFile) |
| 58 | + if err != nil { |
| 59 | + print(err.Error()) |
| 60 | + } |
| 61 | + |
| 62 | +} |
| 63 | +func readAndDecode(fileName string, person *Person, fileType string) { |
| 64 | + file, err := os.Open(fileName) |
| 65 | + if err != nil { |
| 66 | + fmt.Println("Error abriendo el archivo:", err) |
| 67 | + return |
| 68 | + } |
| 69 | + defer file.Close() |
| 70 | + |
| 71 | + data, _ := io.ReadAll(file) |
| 72 | + |
| 73 | + switch fileType { |
| 74 | + case "json": |
| 75 | + err := json.Unmarshal(data, person) |
| 76 | + if err != nil { |
| 77 | + print(err.Error()) |
| 78 | + } |
| 79 | + case "xml": |
| 80 | + err := xml.Unmarshal(data, person) |
| 81 | + if err != nil { |
| 82 | + print(err.Error()) |
| 83 | + } |
| 84 | + } |
| 85 | +} |
0 commit comments