有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用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());

    }
}

如果我错了,请告诉我

提前谢谢


共 (2) 个答案

  1. # 1 楼答案

    如果你调试代码,你会在课堂上看到下面的代码 com.fasterxml.jackson.databind.deser.std.UntypedObjectDeserializer

    ....
    switch (p.getCurrentTokenId()) {
                case JsonTokenId.ID_START_OBJECT:
                    {
                        JsonToken t = p.nextToken();
                        if (t == JsonToken.END_OBJECT) {
                            return new LinkedHashMap<String,Object>(2);
                        }
                    }
                case JsonTokenId.ID_FIELD_NAME:
                    return mapObject(p, ctxt);
    ....
    

    从上面我们可以看到,如果您的类是java.lang.Object,它将执行case JsonTokenId.ID_START_OBJECT,并返回一个LinkedHashMap作为结果

  2. # 2 楼答案

    上面写着线程“main”java。lang.ClassCastException:无法强制转换java。util。LinkedHashMap到com。我dto。Post,这意味着你的ts.jsonToDto()返回一个LinkedHashMap,并且不能转换到你的DTO

    你可以参考here 了解更多信息

    The issue's coming from Jackson. When it doesn't have enough information on what class to deserialize to, it uses LinkedHashMap.

    Since you're not informing Jackson of the element type of your ArrayList, it doesn't know that you want to deserialize into an ArrayList of Accounts. So it falls back to the default.

    他们也给了你解决方案