如何将数据转化成json形式

第一步: 导入fastjson依赖:

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

第二步:创建对象,转换数据,返回即可

 @GetMapping("/queryList")
 public String queryList() throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    List<User> userList =  userService.queryList();
    String set = mapper.writeValueAsString(userList);
    return set;
 }

返回时间对象:

@GetMapping("/queryList01")
public String queryList01() throws JsonProcessingException {
     ObjectMapper mapper = new ObjectMapper();
     Date date = new Date();
     SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM--dd hh:mm:ss");
     String set = mapper.writeValueAsString(simpleDateFormat.format(date));
     return set;
 }

编写util工具类:

public class JsonUtils {
    public static String getJson(Object object,String dateFormate){
        ObjectMapper mapper = new ObjectMapper();
        //不使用时间戳的方式
        mapper.configure(SerializationFeature.CLOSE_CLOSEABLE,false);
        //使用时间戳
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormate);
        mapper.setDateFormat(simpleDateFormat);
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}

配置好工具类之后,调用对象即可:

返回时间戳对象可改变成:

 @GetMapping("/queryList01")
 public String queryList01() throws JsonProcessingException {
    Date date = new Date();
    return JsonUtils.getJson(date,"yyyy-MM-dd HH:mm:ss");
 }

你可能感兴趣的:(java,前端)