|
| 1 | +import com.fasterxml.jackson.core.type.TypeReference; |
| 2 | +import com.fasterxml.jackson.databind.SerializationFeature; |
| 3 | +import com.fasterxml.jackson.dataformat.xml.XmlMapper; |
| 4 | +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; |
| 5 | +import com.google.gson.Gson; |
| 6 | +import com.google.gson.GsonBuilder; |
| 7 | +import com.google.gson.TypeAdapter; |
| 8 | +import com.google.gson.reflect.TypeToken; |
| 9 | +import com.google.gson.stream.JsonReader; |
| 10 | +import com.google.gson.stream.JsonWriter; |
| 11 | + |
| 12 | +import java.io.File; |
| 13 | +import java.io.FileNotFoundException; |
| 14 | +import java.io.FileWriter; |
| 15 | +import java.io.IOException; |
| 16 | +import java.nio.file.Files; |
| 17 | +import java.nio.file.Path; |
| 18 | +import java.time.LocalDate; |
| 19 | +import java.time.format.DateTimeFormatter; |
| 20 | +import java.util.Arrays; |
| 21 | +import java.util.HashSet; |
| 22 | +import java.util.Scanner; |
| 23 | +import java.util.Set; |
| 24 | + |
| 25 | +/** |
| 26 | + * #12 JSON Y XML |
| 27 | + * <dependencies> |
| 28 | + * <dependency> |
| 29 | + * <groupId>com.fasterxml.jackson.dataformat</groupId> |
| 30 | + * <artifactId>jackson-dataformat-xml</artifactId> |
| 31 | + * <version>2.17.2</version> |
| 32 | + * </dependency> |
| 33 | + * <dependency> |
| 34 | + * <groupId>com.fasterxml.jackson.datatype</groupId> |
| 35 | + * <artifactId>jackson-datatype-jsr310</artifactId> |
| 36 | + * <version>2.17.2</version> |
| 37 | + * </dependency> |
| 38 | + * <dependency> |
| 39 | + * <groupId>com.google.code.gson</groupId> |
| 40 | + * <artifactId>gson</artifactId> |
| 41 | + * <version>2.10.1</version> |
| 42 | + * </dependency> |
| 43 | + * </dependencies> |
| 44 | + * |
| 45 | + * @author martinbohorquez |
| 46 | + */ |
| 47 | +public class martinbohorquez { |
| 48 | + |
| 49 | + private static final FileOperation operation = new FileOperation(); |
| 50 | + |
| 51 | + public static void main(String[] args) { |
| 52 | + // Creación de objetos. |
| 53 | + Programmer programmer = new Programmer(); |
| 54 | + programmer.setName("Martin B"); |
| 55 | + programmer.setAge(29); |
| 56 | + programmer.setBirthDate(LocalDate.of(1994, 9, 26)); |
| 57 | + programmer.setLanguages(new HashSet<>(Arrays.asList("Java", "Typescript", "Python"))); |
| 58 | + |
| 59 | + // XML |
| 60 | + String stringXml = "data/martinDev.xml"; |
| 61 | + File fileXml = operation.create(stringXml); |
| 62 | + // Serialización |
| 63 | + XMLManager<Programmer> xmlManager = new XMLManager<>(fileXml.toPath()); |
| 64 | + xmlManager.serialize(programmer); |
| 65 | + // Deserialización |
| 66 | + TypeReference<Programmer> typeReference = new TypeReference<>() { |
| 67 | + }; |
| 68 | + Programmer programmerFromXml = xmlManager.deserialize(typeReference); |
| 69 | + System.out.println(programmerFromXml); |
| 70 | +// operation.delete(fileXml); |
| 71 | + |
| 72 | + //JSON |
| 73 | + String stringJson = "data/martinDev.json"; |
| 74 | + File fileJson = operation.create(stringJson); |
| 75 | + // Serialización |
| 76 | + JSONManager<Programmer> jsonManage = new JSONManager<>(fileJson.toPath()); |
| 77 | + jsonManage.serialize(programmer); |
| 78 | + // Deserialización |
| 79 | + Programmer programmerFromJson = jsonManage.deserialize(TypeToken.get(Programmer.class)); |
| 80 | + System.out.println(programmerFromJson); |
| 81 | +// operation.delete(fileJson); |
| 82 | + } |
| 83 | + |
| 84 | + private static class FileOperation { |
| 85 | + |
| 86 | + private static void printFileEmpty() { |
| 87 | + System.out.println("El archivo se encuentra vacío, no tiene registros!"); |
| 88 | + } |
| 89 | + |
| 90 | + private static void printfException(IOException e, String process) { |
| 91 | + System.out.printf("Error al '%s' en el archivo: '%s'%n", process, e.getMessage()); |
| 92 | + } |
| 93 | + |
| 94 | + private File create(String string) { |
| 95 | + File file = new File(string); |
| 96 | + if (file.getParentFile() != null) file.getParentFile().mkdirs();// Crear la carpeta si no existe |
| 97 | + return file; |
| 98 | + } |
| 99 | + |
| 100 | + private void write(File file, String string) { |
| 101 | + try (FileWriter writer = new FileWriter(file, true); Scanner reader = new Scanner(file)) { |
| 102 | + writer.append(string).append(System.lineSeparator()); |
| 103 | + if (!reader.hasNext()) System.out.printf("Archivo '%s' creado!%n", file); |
| 104 | + else System.out.printf("Archivo '%s' modificado!%n", file); |
| 105 | + } catch (IOException e) { |
| 106 | + printfException(e, "escribir"); |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + private void read(File file) { |
| 111 | + if (file == null || file.length() == 0) printFileEmpty(); |
| 112 | + else { |
| 113 | + try (Scanner reader = new Scanner(file)) { |
| 114 | + System.out.println("Contenido del archivo: "); |
| 115 | + while (reader.hasNext()) System.out.println(reader.nextLine()); |
| 116 | + } catch (FileNotFoundException e) { |
| 117 | + printfException(e, "leer"); |
| 118 | + } |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + private void delete(File file) { |
| 123 | + if (file != null && file.delete()) { |
| 124 | + if (file.getParentFile() != null && file.getParentFile().delete()) |
| 125 | + System.out.printf("Folder '\\%s' eliminado correctamente!%n", file.getParentFile().toString()); |
| 126 | + System.out.printf("Archivo '%s' eliminado correctamente!%n", file); |
| 127 | + } |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + private static class Programmer { |
| 132 | + private String name; |
| 133 | + private Integer age; |
| 134 | + private LocalDate birthDate; |
| 135 | + private Set<String> languages; |
| 136 | + |
| 137 | + public String getName() { |
| 138 | + return name; |
| 139 | + } |
| 140 | + |
| 141 | + public void setName(String name) { |
| 142 | + this.name = name; |
| 143 | + } |
| 144 | + |
| 145 | + public Integer getAge() { |
| 146 | + return age; |
| 147 | + } |
| 148 | + |
| 149 | + public void setAge(Integer age) { |
| 150 | + this.age = age; |
| 151 | + } |
| 152 | + |
| 153 | + public LocalDate getBirthDate() { |
| 154 | + return birthDate; |
| 155 | + } |
| 156 | + |
| 157 | + public void setBirthDate(LocalDate birthDate) { |
| 158 | + this.birthDate = birthDate; |
| 159 | + } |
| 160 | + |
| 161 | + public Set<String> getLanguages() { |
| 162 | + return languages; |
| 163 | + } |
| 164 | + |
| 165 | + public void setLanguages(Set<String> languages) { |
| 166 | + this.languages = languages; |
| 167 | + } |
| 168 | + |
| 169 | + @Override |
| 170 | + public String toString() { |
| 171 | + return "Programmer : [name=" + name + ", age=" + age + ", birthDate=" + birthDate + ", languages=" + languages |
| 172 | + + "]"; |
| 173 | + } |
| 174 | + } |
| 175 | + |
| 176 | + private static class XMLManager<T> { |
| 177 | + private XmlMapper xmlMapper; |
| 178 | + private Path path; |
| 179 | + |
| 180 | + public XMLManager(Path path) { |
| 181 | + this.path = path; |
| 182 | + this.xmlMapper = XmlMapper.builder() |
| 183 | + .enable(SerializationFeature.INDENT_OUTPUT) |
| 184 | + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) |
| 185 | + .build(); |
| 186 | + xmlMapper.registerModule(new JavaTimeModule()); |
| 187 | + } |
| 188 | + |
| 189 | + public void serialize(T object) { |
| 190 | + try { |
| 191 | + this.xmlMapper.writeValue(this.path.toFile(), object); |
| 192 | + } catch (Exception e) { |
| 193 | + e.printStackTrace(System.out); |
| 194 | + } |
| 195 | + } |
| 196 | + |
| 197 | + public T deserialize(TypeReference<T> typeReference) { |
| 198 | + try { |
| 199 | + T objectDeserialize = this.xmlMapper.readValue(this.path.toFile(), typeReference); |
| 200 | + return objectDeserialize; |
| 201 | + } catch (Exception e) { |
| 202 | + e.printStackTrace(System.out); |
| 203 | + } |
| 204 | + return null; |
| 205 | + } |
| 206 | + } |
| 207 | + |
| 208 | + private static class JSONManager<T> { |
| 209 | + private Path path; |
| 210 | + private Gson gson; |
| 211 | + |
| 212 | + public JSONManager(Path path) { |
| 213 | + this.path = path; |
| 214 | + this.gson = new GsonBuilder() |
| 215 | + .setPrettyPrinting() // This enables pretty printing |
| 216 | + .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) |
| 217 | + .create(); |
| 218 | + } |
| 219 | + |
| 220 | + public void serialize(T object) { |
| 221 | + try { |
| 222 | + String jsonString = gson.toJson(object); |
| 223 | + Files.writeString(path, jsonString); |
| 224 | + } catch (IOException e) { |
| 225 | + e.printStackTrace(System.out); |
| 226 | + } |
| 227 | + } |
| 228 | + |
| 229 | + public T deserialize(TypeToken<T> typeToken) { |
| 230 | + try { |
| 231 | + byte[] data = Files.readAllBytes(path); |
| 232 | + T object = gson.fromJson(new String(data), typeToken.getType()); |
| 233 | + return object; |
| 234 | + } catch (IOException e) { |
| 235 | + e.printStackTrace(); |
| 236 | + } |
| 237 | + return null; |
| 238 | + } |
| 239 | + } |
| 240 | + |
| 241 | + // Type Adapter for LocalDate |
| 242 | + private static class LocalDateTypeAdapter extends TypeAdapter<LocalDate> { |
| 243 | + private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE; |
| 244 | + |
| 245 | + @Override |
| 246 | + public LocalDate read(JsonReader jsonReader) throws IOException { |
| 247 | + if (jsonReader.peek() == com.google.gson.stream.JsonToken.NULL) { |
| 248 | + jsonReader.nextNull(); |
| 249 | + return null; |
| 250 | + } else { |
| 251 | + return LocalDate.parse(jsonReader.nextString(), FORMATTER); |
| 252 | + } |
| 253 | + } |
| 254 | + |
| 255 | + @Override |
| 256 | + public void write(JsonWriter jsonWriter, LocalDate localDate) throws IOException { |
| 257 | + if (localDate == null) { |
| 258 | + jsonWriter.nullValue(); |
| 259 | + } else { |
| 260 | + jsonWriter.value(localDate.format(FORMATTER)); |
| 261 | + } |
| 262 | + } |
| 263 | + } |
| 264 | +} |
0 commit comments