Gson解析本地JSON文件报Expected BEGIN_ARRAY but was STRING错误求助
问题根因
- 核心错误1:
Gson.fromJson()方法的第一个入参直接传入了文件名字符串"json_file.json",Gson会直接解析该字符串本身而非读取对应文件的JSON内容,因此解析时第一个字符是j而非预期的数组起始符[,直接触发你遇到的异常。 - 次要错误2:你定义的
ControlProperty实体类中minlength、maxlength字段为int类型,但JSON文件中对应字段是用双引号包裹的字符串格式(如"minlength": "1"),修复第一个问题后会继续抛出类型不匹配异常。 - 可选兼容问题:实体类未声明JSON中存在的
controlId、required等字段,Gson默认会忽略未知字段,不影响核心解析,如有需要可补充对应成员变量即可。
修复步骤
- 正确读取本地JSON文件内容,再传入Gson解析
不同运行环境读取文件的方式不同,以下是常见场景的示例代码:
- 普通Java项目读取resources目录下文件:
// 读取文件内容为字符串 InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("json_file.json"); String jsonContent = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8); // 再解析JSON ArrayList<ControlProperty> controlProperty = new Gson().fromJson(jsonContent, new TypeToken<List<ControlProperty>>() {}.getType());
- Android项目读取assets目录下文件:
InputStream inputStream = getAssets().open("json_file.json"); int size = inputStream.available(); byte[] buffer = new byte[size]; inputStream.read(buffer); inputStream.close(); String jsonContent = new String(buffer, StandardCharsets.UTF_8); ArrayList<ControlProperty> controlProperty = new Gson().fromJson(jsonContent, new TypeToken<List<ControlProperty>>() {}.getType());
- 修正实体类字段类型
将ControlProperty类中两个int字段改为String类型即可兼容JSON格式:
// 修改前 // private int minlength; // private int maxlength; // 修改后 private String minlength; private String maxlength;
如果需要保留int类型,也可以通过Gson配置开启宽松解析自动转换字符串数字:
Gson gson = new GsonBuilder() .setLenient() .create(); ArrayList<ControlProperty> controlProperty = gson.fromJson(jsonContent, new TypeToken<List<ControlProperty>>() {}.getType());
内容的提问来源于stack exchange,提问作者DanIke
相关产品推荐
相关产品推荐

