SpringBoot 返回Json一直报错问题
- 错误如下
我的错误原因是重写了 WebMvcConfigurationSupport 配置类,开始配置类是为了解决乱码问题而重写的,但是没注意到JSON问题
@Configuration
public class CharsetConfig extends WebMvcConfigurationSupport {
@Bean
public HttpMessageConverter<String> responseBodyConverter() {
StringHttpMessageConverter converter = new StringHttpMessageConverter(
Charset.forName("UTF-8"));
return converter;
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//错误代码
//super.configureMessageConverters(converters);
//converters.add(responseBodyConverter());
//修改后代码
GsonHttpMessageConverter gsonHttpMessageConverter=new GsonHttpMessageConverter();
converters.add(gsonHttpMessageConverter);
}
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false);
}
}
默认Json转换器的使用步骤
-
1、在pom.xml中添加meaven依赖
<dependency> <scope>compile</scope> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.3.4.RELEASE</version> </dependency>
此依赖默认加入jackjson-databinding作为JSON处理器,此时不需要额外的处理器就能返回一段JSON了
-
2、新建实体类
package com.hwp.pojo; public class User { private int id; private String username; private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
- 3、创建UserController实现类返回User对象即可
@RestController
public class UserController {
@GetMapping("/user123")
public User user123(){
User user=new User();
user.setId(1);
user.setPassword("1222");
user.setUsername("111");
return user;
}
}
运行后浏览器输入