This repository has been archived on 2024-01-25. You can view files and clone it, but cannot push or open issues or pull requests.
SDi-Serialization/src/main/java/Rectangles.java
2023-10-18 09:43:34 +02:00

85 lines
2.6 KiB
Java

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Rectangles class. Contains list of rectangles and methods for importing and exporting rectangles to JSON file.
* @version 1.0
* @author Rémi Heredero
*/
public class Rectangles {
private List<Rectangle> rectangles; // List of rectangles.
private ObjectMapper objectMapper; // Object mapper for JSON serialization.
/**
* Constructor. Initializes rectangles list and object mapper.
*/
public Rectangles() {
rectangles = new ArrayList<Rectangle>();
objectMapper = new ObjectMapper();
}
/**
* Add rectangle to list.
* @param rectangle rectangle to add
*/
public void addRectangle(Rectangle rectangle) {
rectangles.add(rectangle);
}
/**
* Get all rectangles.
* @return list of rectangles
*/
public List<Rectangle> getRectangles() {
return rectangles;
}
/**
* Export rectangles to JSON file.
* @return true if export was successful
*/
public boolean exportToJSON() {
objectMapper.enable(SerializationFeature.INDENT_OUTPUT); // Enable JSON pretty printing.
try {
objectMapper.writeValue(new FileOutputStream("rectangles.json"), rectangles);
return true;
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (JsonMappingException e) {
throw new RuntimeException(e);
} catch (JsonGenerationException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Import rectangles from JSON file.
* @return true if import was successful
*/
public boolean importFromJSON(){
try {
rectangles = objectMapper.readValue(new FileInputStream("rectangles.json"), ArrayList.class);
return true;
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (JsonMappingException e) {
throw new RuntimeException(e);
} catch (JsonGenerationException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}