SpringMVC-lesson08-json-2-2023-03-24

公共类

package com.feijian.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.text.SimpleDateFormat;

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 mapper = new ObjectMapper();
        //不使用时间戳
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
        //自定义日期格式
        SimpleDateFormat sdf =new SimpleDateFormat(dateFormat);
        mapper.setDateFormat(sdf);
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
package com.feijian.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.feijian.pojo.User;
import com.feijian.utils.JsonUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
public class UserController {
    @RequestMapping( "/j1")
    //@ResponseBody //它就不会走视图解析器,它会直接返回一个字符串  或用RestController替代@Controller
    public String json1() throws JsonProcessingException {
        //jackson, ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        User user = new User("飞剑",3,"男");
        String str = mapper.writeValueAsString(user);
        return str;
    }

    @RequestMapping( "/j2")
    //@ResponseBody //它就不会走视图解析器,它会直接返回一个字符串  或用RestController替代@Controller
    public String json2() throws JsonProcessingException {

        List<User> userList =new ArrayList<User>();
        User user1 = new User("飞剑1",1,"男");
        User user2 = new User("飞剑2",2,"男");
        User user3 = new User("飞剑3",3,"男");
        User user4 = new User("飞剑4",4,"男");

        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);

        return JsonUtils.getJson(userList);
    }

    @RequestMapping( "/j3")
    //@ResponseBody //它就不会走视图解析器,它会直接返回一个字符串  或用RestController替代@Controller
    public String json3() throws JsonProcessingException {
        Date date = new Date();
        return JsonUtils.getJson(date);
    }
}
posted @ 2023-03-24 20:59  Rui2022  阅读(11)  评论(0编辑  收藏  举报