简体   繁体   中英

JSON to POJO as Object class using jackson java

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.

It says thread "main" java.lang.ClassCastException: Cannot cast java.util.LinkedHashMap to com.me.dto.Post , which means your ts.jsonToDto() returns a LinkedHashMap and cannot be cast to your DTO.

You can refer here to have more information.

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.

They also gave you solutions there.

If you debug the code,you will see the code below in class 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);
....

From the above,we can see,if your Class is java.lang.Object ,it will perform the case JsonTokenId.ID_START_OBJECT ,and return a LinkedHashMap as a result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM