var obj = JSON.parse('{"a":"hello","b":"world"}');
console.log(obj);
const json = JSON.stringify({a:'hello',b:'world'});
console.log(json);
json的简述
服务于ajax,ajax可以进行异步请求,返回的是json字符格式
一个小呆萌
@RequestMapping("json1")
public String json1() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
//创建对象
Demo demo = new Demo(1,"小张");
System.out.println(demo);
//转换为json字符串
String str = mapper.writeValueAsString(demo);
System.out.println(str);
return str;
}
返回时间类型的json (时间戳)
@RequestMapping("json2")
public String json2() throws JsonProcessingException {
Date date = new Date();
return new ObjectMapper().writeValueAsString(date);
}
修改时间格式
@RequestMapping("json3")
public String json3() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
//关闭时间戳
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
//设置时间格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//指定设置后的格式
mapper.setDateFormat(sdf);
//时间对象
Date date = new Date();
return mapper.writeValueAsString(date);
}
封装
@RequestMapping("json4")
public String json4() throws JsonProcessingException {
Date date = new Date();
return JsonUtils.getJson(date);
}
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){
try{
ObjectMapper mapper = new ObjectMapper();
//关闭时间戳
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
//设置时间格式
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
//指定设置后的格式
mapper.setDateFormat(sdf);
return mapper.writeValueAsString(object);
}catch (JsonProcessingException e){
e.printStackTrace();
}
return null;
}
}