Skip to content

Commit 997faea

Browse files
authored
Merge pull request mouredev#2444 from ASJordi/main
#12 - Java
2 parents cfe79a9 + f98b19c commit 997faea

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import com.fasterxml.jackson.core.JsonProcessingException;
2+
import com.fasterxml.jackson.databind.ObjectMapper;
3+
import com.fasterxml.jackson.databind.SerializationFeature;
4+
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
5+
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
6+
7+
import java.io.File;
8+
import java.io.IOException;
9+
import java.time.LocalDate;
10+
import java.util.List;
11+
12+
public class Main {
13+
14+
public static void main(String[] args) throws IOException {
15+
crearJson();
16+
leerJson();
17+
crearXml();
18+
leerXml();
19+
}
20+
21+
record Pojo(String nombre, Integer edad, LocalDate fechaNacimiento, List<String> lenguajes) {}
22+
23+
static void crearJson() {
24+
Pojo pojo = new Pojo("Jordi", 25, LocalDate.of(1995, 8, 1), List.of("Java", "Kotlin", "Scala"));
25+
26+
ObjectMapper mapper = new ObjectMapper();
27+
mapper.registerModule(new JavaTimeModule());
28+
29+
try {
30+
mapper.writeValue(new File("pojo.json"), pojo);
31+
} catch (Exception e) {
32+
e.printStackTrace();
33+
}
34+
}
35+
36+
static void leerJson() {
37+
ObjectMapper mapper = new ObjectMapper();
38+
mapper.registerModule(new JavaTimeModule());
39+
File jsonFile = new File("pojo.json");
40+
41+
try {
42+
var pojo = mapper.readValue(jsonFile, Pojo.class);
43+
System.out.println(pojo);
44+
jsonFile.delete();
45+
System.out.println("Fichero eliminado");
46+
} catch (Exception e) {
47+
e.printStackTrace();
48+
}
49+
}
50+
51+
static void crearXml() {
52+
Pojo pojo = new Pojo("Jordi", 25, LocalDate.of(1995, 8, 1), List.of("Java", "Kotlin", "Scala"));
53+
ObjectMapper xmlMapper = new XmlMapper();
54+
xmlMapper.registerModule(new JavaTimeModule());
55+
xmlMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
56+
57+
try {
58+
xmlMapper.writeValue(new File("pojo.xml"), pojo);
59+
} catch (Exception e) {
60+
e.printStackTrace();
61+
}
62+
}
63+
64+
static void leerXml() {
65+
ObjectMapper xmlMapper = new XmlMapper();
66+
xmlMapper.registerModule(new JavaTimeModule());
67+
File xmlFile = new File("pojo.xml");
68+
69+
try {
70+
var pojo = xmlMapper.readValue(xmlFile, Pojo.class);
71+
System.out.println(pojo);
72+
xmlFile.delete();
73+
System.out.println("Fichero eliminado");
74+
} catch (Exception e) {
75+
e.printStackTrace();
76+
}
77+
}
78+
79+
/**
80+
* Maven dependencies:
81+
* jackson-databind
82+
* jackson-datatype-jsr310
83+
* jackson-dataformat-xml
84+
*/
85+
86+
}

0 commit comments

Comments
 (0)