导入JackJSON包
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.1</version>
</dependency>
json 数据中文乱码 在springMVC中配置
<mvc:annotation-driven>
<mvc:message-converters>
<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>
用jackJson转json的类
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.text.SimpleDateFormat;
/**
* @Description:
* @ClassName: jsonUtil
* @Date: 2021/3/31 10:54
* @Author: bm
* @Version: 1.0
* @Since: JDK 1.8
*/
public class JsonUtil {
public static String getJson(Object object){
return getJson(object,"yyyy-MM-dd HH:mm:ss");
}
public static String getJson(Object object, String dateFormat){
ObjectMapper mapper = new ObjectMapper();
//不使用时间戳而是使用自己的格式 mapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS,false);
SimpleDateFormat ft = new SimpleDateFormat(dateFormat);
try {
return mapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
调用工具类
import com.tv189.entity.User;
import com.tv189.utils.JsonUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;
/**
* @Description:
* @ClassName: UserController
* @Date: 2021/3/31 10:51
* @Author: bm
* @Version: 1.0
* @Since: JDK 1.8
*/
@Controller
public class UserController {
@RequestMapping("/test1")
@ResponseBody
public String json(){
List<User> userList = new ArrayList<>();
User user1 = new User("1号",2,"男");
User user2 = new User("2号",3,"nv");
userList.add(user1);
userList.add(user2);
return JsonUtil.getJson(userList);
}
}