【问题标题】:Reading JSON from a file using GSON使用 GSON 从文件中读取 JSON
【发布时间】:2021-01-29 14:39:39
【问题描述】:

我尝试简单的读取json文件,然后创建类对象,但是不起作用,BufferedReader甚至不读取文件,虽然在示例中是直接传递给GSON,但是添加了依赖到 pom 文件。

json

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

【问题讨论】:

  • 您的 json 文件无效。每个surname 后面都有一个昏迷状态。另外,您可以添加异常/错误消息吗?
  • “它不起作用”是什么意思? --- “BufferedReader 甚至不读取文件” 是什么意思?你是怎么想到的? --- 当你尝试运行代码时实际发生了什么?
  • 线程“主”com.google.gson.JsonSyntaxException 中的异常:java.lang.IllegalStateException:应为 BEGIN_OBJECT,但在 com.google.gson.internal.bind 的第 1 列第 1 列路径 $ 为字符串.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:224

标签: java json gson


【解决方案1】:

正如 theBittor 所说:您必须删除姓氏后面的逗号。然后main就可以读取你的json了。

顺便说一下,你的读者应该被 try-finally 包围,或者使用 Java 的 Autoclose 特性

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多