1. 导入依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.0</version>
</dependency>
2. 创建实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Myuser {
private String username;
private String passowrd;
private int age;
}
3. 解决JSON中文乱码问题
在springmvc-servlet.xml中的注解驱动支持中添加以下内容
<!-- Spring MVC注解驱动支持(解决JSON乱码问题) -->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
3. 编写Controller
@ResponseBody 使用此注解当前方法不走视图解析器,而是直接返回一个字符串
@RestController 使用此注解当前类中所有方法不走视图解析器,而是直接返回一个字符串
@ResponseBody
@GetMapping("/getalluser")
public String getAllUser() throws JsonProcessingException {
//jackson objectMapper
ObjectMapper objectMapper = new ObjectMapper();
Myuser myuser = new Myuser("施一帆", "shiyifan1230", 1);
String jsonstring = objectMapper.writeValueAsString(myuser);
return jsonstring;
}
使用jackson的ObjectMapper.writeValueAsString()将对象转换为json字符串返回
4. JSON返回时间
因为objectMapper将时间解析后的默认格式为:Timestamp(时间戳),因此我们需要将时间格式进行修改得到我们想要的时间格式
1.纯java解决方案
@ResponseBody
@GetMapping("/gettime")
public String gettime() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String jsonstring = objectMapper.writeValueAsString(dateFormat.format(date));
return jsonstring;
}
2.ObjectMapper解决方案
@ResponseBody
@GetMapping("/gettime")
public String gettime() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
Date date = new Date();
//不使用时间戳的方式
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
//自定义日期格式对象
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//指定日期格式
objectMapper.setDateFormat(sdf);
String jsonstring = objectMapper.writeValueAsString(date);
return jsonstring;
}
}
5. 将JSON字符串转换为Java对象
@ResponseBody
@GetMapping("/adduser")
public String addUser() throws JsonProcessingException {
//jackson objectMapper
ObjectMapper objectMapper = new ObjectMapper();
//模拟得到前端传入的JSON字符串
String user = getAllUser();
Myuser myuser = objectMapper.readValue(user, Myuser.class);
return myuser.toString();
}