JSON data conversion issue with Generic in Jersy REST web services

Viewed 21

When I created a REST API with Generic in Jersy, I got the following error when getting the element from the map. I can retrieve the whole map as JSON but Couldn't get individual objects from the map. I can get all the students when I call the getStudents() method, but getStudent(id) method gives an error because it is not converted to Student.

java.lang.ClassCastException: class java.util.LinkedHashMap cannot be cast to class vau.ac.lk.StudentAPIMap.Model.Student

    package vau.ac.lk.StudentAPIMap.Model;
    
    import javax.xml.bind.annotation.XmlRootElement;
    
    @XmlRootElement
    public class Student {
        private String regNo;
        private String name;
        private int age;
        private char gender;
        
        //an empty constructor for JSON conversion
        public Student() {
            
        }
        
        public Student(String regNo, String name, int age, char gender) {
            super();
            this.regNo = regNo;
            this.name = name;
            this.age = age;
            this.gender = gender;
        }
        public String getRegNo() {
            return regNo;
        }
        public void setRegNo(String regNo) {
            this.regNo = regNo;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        public char getGender() {
            return gender;
        }
        public void setGender(char gender) {
            this.gender = gender;
        }
        
        
    
    }
    package vau.ac.lk.StudentAPIMap.Repo;
    
    import java.io.File;
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.Map;
    
    import com.fasterxml.jackson.core.exc.StreamWriteException;
    import com.fasterxml.jackson.core.type.TypeReference;
    import com.fasterxml.jackson.databind.DatabindException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    
    public class Repo<K,V> {
        private Map<K, V> map=new HashMap<K,V>();
        private ObjectMapper mapper = new ObjectMapper();
        private String filePath;
        
        public void setFilePath(String filePath) {
            this.filePath = filePath;
        }
    
        public void writeJson(String file, Map<K, V> m) {
            try {
                mapper.writerWithDefaultPrettyPrinter().writeValue(new File(filePath), m);
            } catch (StreamWriteException e) {
                System.out.println(e.getMessage());
            } catch (DatabindException e) {
                System.out.println(e.getMessage());
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
        
        public Map<K, V> readJson(String file, Map<K, V> m) {
            try {
                byte[] jsonData = Files.readAllBytes(Paths.get(filePath));
                m = mapper.readValue(jsonData, new TypeReference<Map<K, V>>() {
                });
    
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
            return m;
        }
        
        public Collection<V>getAllEle(){
            map = readJson(filePath, map);
            return map.values();
        }
        
        public V getEle(K id) {
            map = readJson(filePath, map);
            System.out.println(map.get(id));
            return map.get(id);
        }
        
        public void insert(K id,V ele) {
            map.put(id, ele);
            writeJson(filePath, map);
        }
        
        public void update(K id,V ele) {
            map.put(id, ele);
            writeJson(filePath, map);
        }
        
        public void delete(K id) {
            map.remove(id);
            writeJson(filePath, map);
        }
    }
package vau.ac.lk.StudentAPIMap.Repo;

import vau.ac.lk.StudentAPIMap.Model.Student;

public class StudentRepo extends Repo<String, Student> {
    public StudentRepo(String JsonfilePath) {
        setFilePath(JsonfilePath);
    }
}

package vau.ac.lk.StudentAPIMap;

import java.util.Collection;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import vau.ac.lk.StudentAPIMap.Model.Student;
import vau.ac.lk.StudentAPIMap.Repo.StudentRepo;

@Path("/student")
public class StudentResource {
    String path= "C:/Users/Dell/eclipse-workspace/IT2234/StudentAPIMap/src/main/resources/StudentsData.json";
    public StudentRepo repo = new StudentRepo(path);

    @POST
    @Path("/add")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String addStudent(Student newStudent) {
        if (newStudent == null) {
            return "Bad post request";
        } else {
            repo.insert(newStudent.getRegNo(), newStudent);
            return "A new student added to file !";
        }
    }

    @GET
    @Path("/all")
    @Produces(MediaType.APPLICATION_JSON)
    public Collection<Student> getStudents() {
        System.out.println("hello !");
        return repo.getAllEle();
    }

    @GET
    @Path("/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Student getStudent(@PathParam("id") String id) {
        Student student=repo.getEle(id);
        return student;
    }

    @DELETE
    @Path("/{id}")
    public String deleteStudent(@PathParam("id") String id) {
        if (repo.getEle(id) == null) {
            return "Student not found";
        } else {
            repo.delete(id);
            return "the student deleted from  the file !";
        }
    }

    @PUT
    @Path("/update")
    public String updateStudent(Student student) {
        if (repo.getEle(student.getRegNo()) == null) {
            return "Student not found";
        } else {
            repo.update(student.getRegNo(), student);
            return "the student detail updated!";
        }
    }

}

<dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
            <!-- use the following artifactId if you don't need servlet 2.x compatibility -->
            <!-- artifactId>jersey-container-servlet</artifactId -->
        </dependency>
        <dependency>
            <groupId>org.glassfish.jaxb</groupId>
            <artifactId>jaxb-runtime</artifactId>
            <version>2.3.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.2.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-json-jackson -->
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
        </dependency>


    </dependencies>
0 Answers
Related