Baris
Baris

Reputation: 29

Method return null list

I read a json file with this method.

 public class StudentListJson {
    
        public static List<Student> getStudentList() throws IOException {
              ObjectMapper mapper = new ObjectMapper();
              List<Student> studentList = null;
              String fileName = "C:/Users/bar1s/IdeaProjects/Week4/src/main/java/student.json"; 
    
              String stringJson=new String(Files.readAllBytes(Paths.get(fileName)));
    
              studentList=Arrays.asList(mapper.readValue(stringJson,new TypeReference<>(){}));
    
              ProcessController.isReaded=true;
              return studentList;
          }
          
    }

json file :

 [
    {"name":"name1", "surname":"surname1", "age": 18},
    {"name":"name2", "surname":"surname2", "age": 19},
    {"name":"name3", "surname":"surname3", "age": 20},
    {"name":"name4", "surname":"surname4", "age": 21}
  ]

With this class I try to get list of json and print it but the studentList is null.

public class ReadJson implements Runnable  {


    public static List<Student> studentList;

    @Override
    public void run() {
        try{
            System.out.println("Reading thread is sleeping");
            Thread.sleep(1000);

            studentList = StudentListJson.getStudentList();
            studentList.stream().forEach(x -> System.out.println(x.toString()));



        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Student class.

public class Student {

    private String name;
    private String surname;
    private int age;

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", surname='" + surname + '\'' +
                ", age=" + age +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

getStudentList method can read the file and inside that method i can print all list but when I try return that list then I try print that list in ReadJson class that list get null. Why?

This code return null, this is my problem.

   studentList = StudentListJson.getStudentList();

Upvotes: 1

Views: 199

Answers (1)

RainerZufall
RainerZufall

Reputation: 153

did you try to include the desired type of list elements to the TypeReference?

new TypeReference<Student>() { }

Upvotes: 1

Related Questions