mybatis(Jackson:Controller返回JSON数据(集合、日期、日期工具类)、FastJson)

1、Jackson的使用

(1)概念

Jackson是目前比较好的json解析工具,还有阿里巴巴的fastjson等等

(2)导入依赖

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>

(3)创建一个Teacher的实体类:

@Getter
@Setter
@ToString
public class Teacher {
    private String teacherno;
    private String tname;
    private String major;
    private String prof;
    private String department;
}

这里用到的是Lombok插件

(4)创建处理器:

@Controller
@RequestMapping("/teacher")
public class TeacherController {
    @GetMapping(value = "/t1",produces = "application/json;charset=utf-8")//中文乱码
    @ResponseBody//加上之后就不会走视图解析器,返回的是一个字符串
    public String testModelMap(ModelMap modelMap) throws JsonProcessingException {
        ObjectMapper objectMapper=new ObjectMapper();
        Teacher teacher=new Teacher("202011","张","jisuanji","laoshi","xxgc");
        String str=objectMapper.writeValueAsString(teacher);
        return str;
    }
}

mybatis(Jackson:Controller返回JSON数据(集合、日期、日期工具类)、FastJson)

 可以看出,返回的结果是一个json格式的字符串,在这里要处理中文乱码问题,因为返回的是一个字符串,因此不需要视图解析器,要将它屏蔽掉

(5)乱码问题优化

<mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"></constructor-arg>
            </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"></property>
                    </bean>
                </property>
            </bean>

        </mvc:message-converters>
    </mvc:annotation-driven>

直接在springmvc.xml中配置,就不需要在每一个处理器中配置解决JSON的中文乱码的代码了

(6)RestController注解:

@RestController//只返回字符串
@RequestMapping("/teacher")
public class TeacherController {
    @GetMapping(value = "/t1")//中文乱码
    public String testModelMap(ModelMap modelMap) throws JsonProcessingException {
        ObjectMapper objectMapper=new ObjectMapper();
        Teacher teacher=new Teacher("202011","张","jisuanji","laoshi","xxgc");
        String str=objectMapper.writeValueAsString(teacher);
        return str;
    }
}

不需要添加屏蔽视图解析器的代码,直接添加此注解,处理器就只返回字符串

2、返回集合

@RestController//只返回字符串
@RequestMapping("/teacher")
public class TeacherController {
    @GetMapping(value = "/t1")//中文乱码
    public String testModelMap(ModelMap modelMap) throws JsonProcessingException {
        ObjectMapper objectMapper=new ObjectMapper();
        List<Teacher> teacherList=new ArrayList<Teacher>();
        Teacher teacher1=new Teacher("202011","张","jisuanji","laoshi",
                "xxgc");
        Teacher teacher2=new Teacher("202012","张","jisuanji","laoshi",
                "xxgc");
        Teacher teacher3=new Teacher("202013","张","jisuanji","laoshi",
                "xxgc");
        Teacher teacher4=new Teacher("202014","张","jisuanji","laoshi",
                "xxgc");
        teacherList.add(teacher1);
        teacherList.add(teacher2);
        teacherList.add(teacher3);
        teacherList.add(teacher4);
        String str=objectMapper.writeValueAsString(teacherList);
        return str;
    }
}

测试:

mybatis(Jackson:Controller返回JSON数据(集合、日期、日期工具类)、FastJson)

 中括号代表一个集合,大括号代表一个json对象

3:、日期的格式化输出

(1)传统方式:

@RestController//只返回字符串
@RequestMapping("/teacher")
public class TeacherController {
    @GetMapping(value = "/t1")//中文乱码
    public String testModelMap(ModelMap modelMap) throws JsonProcessingException {
        ObjectMapper objectMapper=new ObjectMapper();
        Date date=new Date();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat();
        return objectMapper.writeValueAsString(simpleDateFormat.format(date));
    }
}

mybatis(Jackson:Controller返回JSON数据(集合、日期、日期工具类)、FastJson)

 (2)ObjectMapper 方式:

@RestController//只返回字符串
@RequestMapping("/teacher")
public class TeacherController {
    @GetMapping(value = "/t1")//中文乱码
    public String testModelMap(ModelMap modelMap) throws JsonProcessingException {
        ObjectMapper objectMapper=new ObjectMapper();
        //不使用时间戳的方式
        objectMapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS,false);
        //自定义日期格式
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd:ss");
        objectMapper.setDateFormat(simpleDateFormat);
        Date date=new Date();
        return objectMapper.writeValueAsString(date);
    }
}

mybatis(Jackson:Controller返回JSON数据(集合、日期、日期工具类)、FastJson)

4、工具类

(1)定义工具类:

public class JsonUtils {
    public static String getJson(Object object,String dateFormat){
        ObjectMapper objectMapper=new ObjectMapper();
        //不使用时间戳的方式
        objectMapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS,false);
        //自定义日期格式
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat(dateFormat);
        objectMapper.setDateFormat(simpleDateFormat);
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}

(2)测试工具类:

@RestController//只返回字符串
@RequestMapping("/teacher")
public class TeacherController {
    @GetMapping(value = "/t1")//中文乱码
    public String testModelMap(ModelMap modelMap) throws JsonProcessingException {
         Date date=new Date();
         return JsonUtils.getJson(date,"yyyy-MM-dd HH:mm:ss");
    }
}

(3)如果只传递一个参数:

public class JsonUtils {
    public static String getJson(Object object){
        return getJson(object,"yyyy-MM-dd HH:mm:ss");
    }
    public static String getJson(Object object,String dateFormat){
        ObjectMapper objectMapper=new ObjectMapper();
        //不使用时间戳的方式
        objectMapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS,false);
        //自定义日期格式
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat(dateFormat);
        objectMapper.setDateFormat(simpleDateFormat);
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}

上面的方法调用了另外一个方法,体现了代码的复用,只不过时间的格式已经默认

5、FastJson

(1)概念
是阿里开发的一款专门用于java开发的包,可以方便的实现json对象与javaBean对象的转换,实现javaBean对象与JSON字符串的转换、json字符串与java对象的转换

 (2)导入依赖:

<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.10.0</version>
     </dependency>

(3)IDEA需要更新lib(https://www.cnblogs.com/zhai1997/p/12817048.html

mybatis(Jackson:Controller返回JSON数据(集合、日期、日期工具类)、FastJson)

 (4)测试:

@RestController//只返回字符串
@RequestMapping("/teacher")
public class TeacherController {
    @GetMapping(value = "/t1")//中文乱码
    public String testJson(){
        List<Teacher> teacherList=new ArrayList<Teacher>();
        Teacher teacher1=new Teacher("202011","张","jisuanji","laoshi",
                "xxgc");
        Teacher teacher2=new Teacher("202012","张","jisuanji","laoshi",
                "xxgc");
        Teacher teacher3=new Teacher("202013","张","jisuanji","laoshi",
                "xxgc");
        Teacher teacher4=new Teacher("202014","张","jisuanji","laoshi",
                "xxgc");
        teacherList.add(teacher1);
        teacherList.add(teacher2);
        teacherList.add(teacher3);
        teacherList.add(teacher4);
        String string=JSON.toJSONString(teacherList);
        return string;
    }
}

相关推荐