Spring Boot接口读取JSON文件触发MismatchedInputException异常求助
问题:接口读取JSON文件返回数据时出现反序列化异常
代码实现
UserController.java
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.io.IOException; import java.util.List; @RestController @RequestMapping("/api/users") public class UserController { @Autowired private UserService userService; @GetMapping public List<User> getAllUsers() throws IOException { return userService.findAll(); } }
UserService.java
import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.stereotype.Service; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; @Service public class UserService { private static final String FILE_PATH = "C:\\Users\\test\\Users.json"; private final ObjectMapper objectMapper = new ObjectMapper(); private List<User> getUsers() throws IOException { File file = new File(FILE_PATH); if (file.exists()) { return objectMapper.readValue(file, objectMapper.getTypeFactory().constructCollectionType(List.class, User.class)); } return new ArrayList<>(); } public List<User> findAll() throws IOException { return getUsers(); } }
JSON文件内容
[ {"user_id": 9, "username": "user9", "password": "xxxx", "name": "abcd", "college": "test", "is_edited": false, "is_deleted": false, "user_type_id": 1 }, { "user_id": 10, "username": "user10", "password": "xxxx", "name": "abcd", "college": "test", "is_edited": false, "is_deleted": false, "user_type_id": 2 } ]
异常信息
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.util.ArrayList<com.example.demo.User>` from Object value (token `JsonToken.START_OBJECT`) at [Source: REDACTED (`StreamReadFeature.INCLUDE_SOURCE_IN_LOCATION` disabled); line: 1, column: 1] at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59) ~[jackson-databind-2.17.2.jar:2.17.2] at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1767) ~[jackson-databind-2.17.2.jar:2.17.2] at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1541) ~[jackson-databind-2.17.2.jar:2.17.2] at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1488) ~[jackson-databind-2.17.2.jar:2.17.2] at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.handleNonArray(CollectionDeserializer.java:402) ~[jackson-databind-2.17.2.jar:2.17.2]
解决方案
异常核心原因:Jackson尝试将JSON对象反序列化为List<User>,但预期的是JSON数组。按以下步骤排查修复:
修正JSON语法错误
你提供的JSON示例中password字段值xxxx未加双引号,这会导致JSON解析异常,Jackson可能将错误的JSON解析为异常结构。确保所有字符串类型字段值都用双引号包裹,如"password": "xxxx"。同时检查文件是否存在括号不匹配、逗号遗漏等其他语法问题。验证文件路径准确性
确认FILE_PATH指向的是目标JSON文件,避免读取到其他内容不符的文件。可以在getUsers()方法中添加日志输出文件绝对路径,或临时打印文件内容,确认读取的文件是否正确。优化反序列化代码
改用TypeReference简化集合类型指定,代码可读性更强,避免潜在的类型构造错误:import com.fasterxml.jackson.core.type.TypeReference; // ... private List<User> getUsers() throws IOException { File file = new File(FILE_PATH); if (file.exists()) { return objectMapper.readValue(file, new TypeReference<List<User>>() {}); } return new ArrayList<>(); }添加错误排查日志
捕获JSON解析异常并输出详细信息,方便定位问题:import com.fasterxml.jackson.core.JsonProcessingException; import java.nio.file.Files; // ... private List<User> getUsers() throws IOException { File file = new File(FILE_PATH); if (file.exists()) { try { return objectMapper.readValue(file, new TypeReference<List<User>>() {}); } catch (JsonProcessingException e) { System.err.println("JSON解析错误: " + e.getMessage()); System.err.println("文件内容: " + Files.readString(file.toPath())); throw e; } } return new ArrayList<>(); }
内容的提问来源于stack exchange,提问作者lse23
相关产品推荐
相关产品推荐

