使用GSON从文件中阅读JSON

zour9fqk  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(192)

我尝试简单地读取json文件,然后创建类对象,但它不起作用,BufferedReader甚至不读取文件,尽管在示例中它直接传递给GSON,依赖项被添加到pom文件。
詹森

{
  "student": [{
    "name": "Mark",
    "surname": "Ivanov",
    }, {

     "name": "Peter",
    "surname": "Ivanov",
  }]
}

已创建类

public class POJOStudents
{
     String name;
     String surname;

}

public class GeneralStudents {
    List<POJOStudents> student;

}

import java.io.BufferedReader;
import java.io.FileReader;
import com.google.gson.Gson;

    public class Main
    {
        public static void main(String[] args) throws Exception
        {

            Gson gson = new Gson();
            BufferedReader br = new BufferedReader(new FileReader("D:\\student.json"));
            GeneralStudents student = gson.fromJson(br, GeneralStudents.class);

        }
    }
v1l68za4

v1l68za41#

正如Bittor所说:你必须去掉姓氏后面的逗号,这样main才能读到你的json。
顺便说一句,读者应该被try-finally包围,或者使用Java的Autoclose特性

try (BufferedReader br = new BufferedReader(new FileReader("D:\\student.json"))) {
        GeneralStudents student = gson.fromJson(br, GeneralStudents.class);
}

相关问题