JSON

JSON

1、什么是JSON

JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式,目前使用特别广泛。

在后端可以把json理解为Stirng字符串的另一种表达方式

{"name": "QinJiang"}
{"age": "3"}
{"sex": "男"}

这就是一种json字符串表达形式,它代表一个类,name、age、sex是他的三种属性

2、如何给前端传递一个JSON

  • 导入json包

    <dependencies>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.10.2</version>
        </dependency>
    </dependencies>
    
  • 在Controller中创建方法:

    @RequestMapping("/j1")
    public String getJson() throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        User user = new User("张三",13,"男");
        String s = objectMapper.writeValueAsString(user);
        return s;
    }
    
@RequestMapping("/j2")
public String getJson2() throws JsonProcessingException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    objectMapper.setDateFormat(sdf);
    String s = objectMapper.writeValueAsString(date);
    return s;
}

这两个方法里s即代表返回的json字符串

第二个方法中我们想要返回的是date日期类型的数据

但是使用date类型的数据直接返回前端会显示一个时间戳,并不是正常的日期类型

我们需要通过SimpleDateFormat来修改显示格式

objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); 表示不使用时间戳描述日期

objectMapper.setDateFormat(sdf);表示使用sdf格式来描述日期

由于我们需要在很多个方法中使用到JSON字符串,可以把他的方法封装为一个java工具类

public class JsonUtils {

    public static String getJson(Object object){
        return getJson(object,"yyyy-MM-dd HH:ss");
    }
    
    
    
    public static String getJson(Object object,String dateFormat){
        ObjectMapper objectMapper = new ObjectMapper();
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        objectMapper.setDateFormat(sdf);
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

}

创建该工具类后,我们就可以调用其进行简便的返回JSON

@RequestMapping("/j1")
public String getJson() throws JsonProcessingException {
    User user = new User("张三",13,"男");
    return JsonUtils.getJson(user);
}

@RequestMapping("/j2")
public String getJson2() throws JsonProcessingException {
    Date date = new Date();
    String d = "yyyy-MM-dd HH:mm:ss";
    return JsonUtils.getJson(date,d);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值