I'm trying to use DTO to JSON (Write in Json file) and JSON to DTO (Read from JSON file) as a common methods (Generic method to be used by different pojo write/read operations)
Inorder to use as common method, i'm using return type as object.
Below my code
public String dtoToJSON(String appName, Object obj) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
String postJson = mapper.writeValueAsString(obj);
System.out.println(postJson);
// Save JSON string to file
FileOutputStream fileOutputStream = new FileOutputStream("post.json");
mapper.writeValue(fileOutputStream, obj);
fileOutputStream.close();
return appName;
}
public Object jsonToDto() throws IOException {
ObjectMapper mapper = new ObjectMapper();
// Read JSON file and convert to java object
InputStream fileInputStream = new FileInputStream("post.json");
Object obj = mapper.readValue(fileInputStream, Object.class);
fileInputStream.close();
return obj;
}
I'm able to run DTO to JSON (Write in Json file) successfully but when i try to run JSON to DTO (Read from JSON file) i get ClassCastException
My exception: thread "main" java.lang.ClassCastException: Cannot cast java.util.LinkedHashMap to com.me.dto.Post
My main method
public static void main(String[] args) throws IOException {
Transform ts=new Transform();
Post post=(Post)ts.jsonToDto();
// print post object
System.out.println("Printing post details");
System.out.println(post.getId());
System.out.println(post.getTitle());
System.out.println(post.getDescription());
System.out.println(post.getContent());
System.out.println(post.getLastUpdatedAt());
System.out.println(post.getPostedAt());
}
}
Please let me know if i'm wrong.
Thanks in advance.