Skip to content

Commit 3e0a0f4

Browse files
authored
Merge pull request mouredev#2514 from Kenysdev/12.cs
#12 - C#
2 parents b47d8ce + f03550c commit 3e0a0f4

File tree

1 file changed

+169
-0
lines changed

1 file changed

+169
-0
lines changed
Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
/*
2+
╔═══════════════════════════════════════╗
3+
║ Autor: Kenys Alvarado ║
4+
║ GitHub: https://github.com/Kenysdev ║
5+
║ 2024 - C# ║
6+
╚═══════════════════════════════════════╝
7+
-----------------------------------------------
8+
* JSON Y XML
9+
-----------------------------------------------
10+
- son formatos de intercambio de datos que estructuran información.
11+
- JSON (JavaScript Object Notation) y XML (eXtensible Markup Language)
12+
*/
13+
using System.IO;
14+
using System.Text.Json;
15+
using System.Xml;
16+
using System.Xml.Linq;
17+
#pragma warning disable CA1050
18+
public class Program {
19+
static void Main() {
20+
21+
var userDic = new Dictionary<string, object> {
22+
{"name", "Ken"},
23+
{"age", 121},
24+
{"dob", "1903-03-19"},
25+
{"prog_langs", new List<string> { "cs", "py", "vb", "rs", "js" }}
26+
};
27+
// _______________________________________________
28+
// * JSON
29+
// serializar
30+
var options = new JsonSerializerOptions {
31+
WriteIndented = true
32+
};
33+
34+
string json = JsonSerializer.Serialize(userDic, options);
35+
File.WriteAllText("user.json", json);
36+
37+
// Deserializar
38+
string readJson = File.ReadAllText("user.json");
39+
var DesUserJson = JsonSerializer.Deserialize<Dictionary<string, object>>(readJson);
40+
Console.WriteLine(DesUserJson["name"]);
41+
42+
// _______________________________________________
43+
// * XML
44+
// serializar
45+
userDic["prog_langs"] = "cs,py,vb,rs,js";
46+
using (XmlTextWriter writer = new XmlTextWriter("user.xml", null)) {
47+
writer.Formatting = Formatting.Indented;
48+
writer.WriteStartDocument();
49+
writer.WriteStartElement("user");
50+
51+
foreach (var pair in userDic) {
52+
writer.WriteStartElement(pair.Key);
53+
writer.WriteValue(pair.Value);
54+
writer.WriteEndElement();
55+
}
56+
57+
writer.WriteEndElement();
58+
writer.WriteEndDocument();
59+
}
60+
61+
// Deserializar
62+
XDocument doc = XDocument.Load("user.xml");
63+
XElement userElement = doc.Root;
64+
string name = userElement.Element("name").Value;
65+
Console.WriteLine(name);
66+
67+
/* _______________________________________________
68+
* EJERCICIO
69+
* Utilizando la lógica de creación de los archivos anteriores, crea un
70+
* programa capaz de leer y transformar en una misma clase custom de tu
71+
* lenguaje los datos almacenados en el XML y el JSON.
72+
* Borra los archivos.
73+
*/
74+
var theFile = new XmlOrJson("user.json");
75+
var dicUser = theFile.AsDictionary();
76+
Console.WriteLine("\nDocumento JSON");
77+
foreach (var kv in dicUser) {
78+
if (kv.Key != "prog_langs") {
79+
Console.WriteLine($"{kv.Key}: {kv.Value}");
80+
}
81+
}
82+
var progLangs = (List<string>)dicUser["prog_langs"];
83+
Console.WriteLine(string.Join(", ", progLangs));
84+
85+
//_________
86+
var theFile2 = new XmlOrJson("user.xml");
87+
var dicUser2 = theFile2.AsDictionary();
88+
Console.WriteLine("\nDocumento XML");
89+
foreach (var kv in dicUser2) {
90+
if (kv.Key != "prog_langs") {
91+
Console.WriteLine($"{kv.Key}: {kv.Value}");
92+
}
93+
}
94+
var progLangs2 = (List<string>)dicUser2["prog_langs"];
95+
Console.WriteLine(string.Join(", ", progLangs2));
96+
97+
//_________
98+
Console.WriteLine("\nAcceder a sus propiedades");
99+
Console.WriteLine(theFile2.name);
100+
Console.WriteLine(theFile2.age);
101+
Console.WriteLine(theFile2.dob);
102+
File.Delete("user.json");
103+
File.Delete("user.xml");
104+
}
105+
106+
public class XmlOrJson {
107+
private string path;
108+
private string extension;
109+
private Dictionary<string, object> dicUser;
110+
public string name;
111+
public int age;
112+
public string dob;
113+
public List<string> langs;
114+
115+
public XmlOrJson(string path) {
116+
this.path = path;
117+
this.extension = Path.GetExtension(path).ToLower();
118+
this.dicUser = new Dictionary<string, object>();
119+
this.name = string.Empty;
120+
this.age = 0;
121+
this.dob = string.Empty;
122+
this.langs = new List<string>();
123+
}
124+
125+
private void addToDic() {
126+
dicUser["name"] = name;
127+
dicUser["age"] = age;
128+
dicUser["dob"] = dob;
129+
dicUser["prog_langs"] = langs;
130+
}
131+
public Dictionary<string, object> AsDictionary() {
132+
try {
133+
if (extension == ".json") {
134+
string readJson = File.ReadAllText(path);
135+
using (var document = JsonDocument.Parse(readJson)) {
136+
var root = document.RootElement;
137+
name = root.GetProperty("name").GetString();
138+
age = root.GetProperty("age").GetInt32();
139+
dob = root.GetProperty("dob").GetString();
140+
foreach (JsonElement lang in root.GetProperty("prog_langs").EnumerateArray()) {
141+
langs.Add(lang.GetString());
142+
}
143+
addToDic();
144+
return dicUser;
145+
}
146+
147+
} else if (extension == ".xml") {
148+
var doc = XDocument.Load("user.xml");
149+
var userElement = doc.Root;
150+
name = userElement.Element("name").Value;
151+
age = int.Parse(userElement.Element("age").Value);
152+
dob = userElement.Element("dob").Value;
153+
langs = userElement.Element("prog_langs").Value.Split(',').ToList();
154+
155+
addToDic();
156+
return dicUser;
157+
} else {
158+
Console.WriteLine("Archivo no compatible.");
159+
return null;
160+
}
161+
}
162+
catch (Exception ex) {
163+
Console.WriteLine($"Exception: {ex.GetType()}");
164+
return null;
165+
}
166+
}
167+
}
168+
}
169+

0 commit comments

Comments
 (0)