简体   繁体   English

使用 GSON 从文件中读取 JSON

[英]Reading JSON from a file using GSON

I try to simply read the json file, followed by the creation of the class object, but it does not work, BufferedReader does not even read the file, although in the examples it is directly passed to GSON, the dependency is added to the pom file. I try to simply read the json file, followed by the creation of the class object, but it does not work, BufferedReader does not even read the file, although in the examples it is directly passed to GSON, the dependency is added to the pom文件。

json json

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

Created classes创建类

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);
    
        }
    }

As theBittor stated: You have to remove the trailing commas after surname.正如 theBittor 所说:您必须删除姓氏后面的逗号。 Then the main can read your json.然后主可以读取你的json。

By the way your readers should be surrounded by try-finally or use the Autoclose feature of Java with顺便说一句,您的读者应该被 try-finally 包围,或者使用 Java 的 Autoclose 功能

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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