使用jacksonjava将JSON转换为POJO作为对象类
我尝试使用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。我dto。帖子
我的主要方法
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());
}
}
如果我错了,请告诉我
提前谢谢
# 1 楼答案
如果你调试代码,你会在课堂上看到下面的代码
com.fasterxml.jackson.databind.deser.std.UntypedObjectDeserializer
从上面我们可以看到,如果您的类是
java.lang.Object
,它将执行caseJsonTokenId.ID_START_OBJECT
,并返回一个LinkedHashMap作为结果# 2 楼答案
上面写着线程“main”java。lang.ClassCastException:无法强制转换java。util。LinkedHashMap到com。我dto。Post,这意味着你的
ts.jsonToDto()
返回一个LinkedHashMap,并且不能转换到你的DTO你可以参考here 了解更多信息
他们也给了你解决方案