gpt4 book ai didi

java - spring boot - com.fasterxml.jackson.databind.JsonMappingException : Can not deserialize instance of java. util.ArrayList 超出 START_OBJECT

转载 作者:行者123 更新时间:2023-11-30 06:24:47 24 4
gpt4 key购买 nike

我想做的事情:

将 ArrayList 发送到我的 Spring Boot 应用程序并处理它。我可以用我自己的方法做到这一点,但似乎方法不合适。 (请参阅此页面上搜索的部分:“此部分不正确”)

我的ArrayList是什么:

{
"takeCourseModels": [
{
"courseId": "8",
"userId": "12"
},
{
"courseId": "7",
"userId": "12"
}
]
}

我得到什么(错误):

“无法读取文档:无法从第 1 行、第 1 列的 START_OBJECT 标记中反序列化 java.util.ArrayList 的实例;嵌套异常为 com.fasterxml.jackson.databind.JsonMappingException”

在谷歌上搜索这个问题后我学到了什么:

• 我需要反序列化我的数组列表,因为此数组列表不是 JSON 数组。这就是它无法读取的原因。 • 我需要使用ObjectMapper 和其他类来接收它,例如:

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(SomeModel.class, new ProgramDeserializer());

String jsonStr = response.readEntity(String.class);
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(jsonStr);
myObjClass[] objects = mapper.readValue(rootNode.toString(), myObjClass[].class);

• 问题是我没有任何自定义反序列化类(必须有一些默认类),并且我不知道如何将自定义反序列化类集成到我的应用程序中。另外,我有多个端点,其中包括需要反序列化的数组列表,因此我不知道如何创建可用于各种模型的模块化反序列化类。 (下面我只展示了Course模型,还有其他模型需要包含反序列化类)

应用程序类:

我的应用程序

@SpringBootApplication  
public class MyApplication {

@Bean
public FilterRegistrationBean jwtFilter() {
final FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new JwtFilter());
registrationBean.addUrlPatterns("/api/*");

return registrationBean;
}

public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}

CustomWebMvcAutoConfig

@Configuration
@AutoConfigureAfter(DispatcherServletAutoConfiguration.class)
public class CustomWebMvcAutoConfig extends WebMvcConfigurerAdapter {

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>converters) {
for (HttpMessageConverter converter : converters) {
if (converter instanceof org.springframework.http.converter.json.MappingJackson2HttpMessageConverter) {
ObjectMapper mapper = ((MappingJackson2HttpMessageConverter) converter).getObjectMapper();
mapper.registerModule(new Hibernate4Module());
}
}
}

@Override
public void extendMessageConverters(List<HttpMessageConverter<?>converters) {
converters.add(mappingJackson2HttpMessageConverter());
}

@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false));
return converter;
}
}

类(class) Controller

@Controller  
@RequestMapping("/api/")
@SuppressWarnings("unchecked")
public class CourseController {

@Autowired
private ICourseService courseService;

//@PostMapping("take_course")
//public ResponseEntity<VoidtakeCourse(@RequestBody ArrayList<UserCourseuserCourseList) throws EntityNotFoundException {
@PostMapping("take_course")
public ResponseEntity<VoidtakeCourse(@RequestBody String json) throws EntityNotFoundException {

//***(START)THIS PART IS NOT PROPER, I WANT TO DO THE FASTER METHOD***
ArrayList<UserCourseuserCourseList = new ArrayList<>();
ObjectMapper mapper = new ObjectMapper();

JSONObject jsnobject = new JSONObject(json);
JSONArray jsonArray = jsnobject.getJSONArray("takeCourseModels");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
UserCourse userCourse = new UserCourse();
userCourse.setCourseId(Integer.valueOf(explrObject.getString("courseId")));
userCourse.setUserId(Integer.valueOf(explrObject.getString("userId")));
userCourse.setIsRegistered("0");
userCourseList.add(userCourse);
}
//***(END) THIS PART IS NOT PROPER, I WANT TO DO THE FASTER METHOD***

int flag = courseService.takeCourse(userCourseList);
if(flag == 2){
return new ResponseEntity(new ResponseCourse("full", "0"), HttpStatus.OK);
}
return new ResponseEntity(new ResponseCourse("added.", "1"), HttpStatus.OK);
}
}

ICourseService

public interface ICourseService {  
int takeCourse(List<UserCourseuserCourseList);
}

类(class)服务

@Service
public class CourseService implements ICourseService {

@Autowired
private ICourseDAO courseDAO;

@Override
public int takeCourse(List<UserCourseuserCourseList) {

int flag = 2;

for (int i = 0; i < userCourseList.size(); i++) {
if (courseDAO.isUserRegisteredToCourse(userCourseList.get(i))) {
flag = 0;
} else {
courseDAO.takeCourse(userCourseList.get(i));
flag = 1;
}
}

return flag;
}
}

类(class)

@Entity  
@Table(name = "courses")
@JsonIgnoreProperties("inspection")
public class Course implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "course_id")
private int courseId;

@Column(name = "course_name")
private String courseName;

@Column(name = "course_code")
private String courseCode;

@Column(name = "number_of_users")
@ColumnDefault("0")
private String numberOfUsers;

@ManyToOne
@JoinColumn(name = "adminId")
private Admin admin;

@ManyToMany
@JsonIgnore
@JoinTable(name = "user_course",
joinColumns = @JoinColumn(name = "course_id", referencedColumnName = "course_id"),
inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "user_id"))
private List<UseruserList;

public String getNumberOfUsers() {
return numberOfUsers;
}

public void setNumberOfUsers(String numberOfUsers) {
this.numberOfUsers = numberOfUsers;
}

public List<UsergetUserList() {
return userList;
}

public void setUserList(List<UseruserList) {
this.userList = userList;
}

public Admin getAdmin() {
return admin;
}

public void setAdmin(Admin admin) {
this.admin = admin;
}

public int getCourseId() {
return courseId;
}

public void setCourseId(int courseId) {
this.courseId = courseId;
}

public String getCourseName() {
return courseName;
}

public void setCourseName(String courseName) {
this.courseName = courseName;
}

public String getCourseCode() {
return courseCode;
}

public void setCourseCode(String courseCode) {
this.courseCode = courseCode;
}
}

最佳答案

Spring 应该能够使用如下所示的类来处理反序列化(添加 getter 和 setter):

class UserCourseList {
private List<UserCourse> takeCourseModels;
}

class UserCourse {
private long userId;
private long courseId;
}

以及 Controller 中的处理方法:

@PostMapping("take_course")
public ResponseEntity<Void> takeCourse(@RequestBody UserCourseList userCourseList) throws
EntityNotFoundException {

请注意,示例中的 JSON 不是 JSON 数组,而是一个 JSON 对象,其字段是 JSON 数组。这基本上就是异常告诉您的内容。创建一个包装类 UserCourseList 来表示此 JSON 是处理这种情况的最便捷方法。

关于java - spring boot - com.fasterxml.jackson.databind.JsonMappingException : Can not deserialize instance of java. util.ArrayList 超出 START_OBJECT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47424101/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com