【发布时间】:2020-03-18 01:45:00
【问题描述】:
我正在尝试使用 DTO 到 JSON(写入 Json 文件)和 JSON 到 DTO(从 JSON 文件读取)作为常用方法(不同 pojo 写入/读取操作使用的通用方法)
为了作为常用方法,我使用返回类型作为对象。
在我的代码下面
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;
}
我能够成功地将 DTO 运行到 JSON(写入 Json 文件),但是当我尝试将 JSON 运行到 DTO(从 JSON 文件中读取)时,我得到 ClassCastException
我的例外: 线程“主”java.lang.ClassCastException:无法将 java.util.LinkedHashMap 转换为 com.me.dto.Post
我的主要方法
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());
}
}
如果我错了,请告诉我。
提前致谢。
【问题讨论】:
-
@Derin 它没有使用 json 文件的读写。
标签: java json spring-boot java-8 jackson