後端json格式資訊傳送前端各種方法
阿新 • • 發佈:2022-06-01
1,後端程式碼
package wsh.controller; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; 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 wsh.pojo.User; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; @RestController public class userController { // 物件資訊傳送 @RequestMapping(value = "j1") public String json01() throws JsonProcessingException { ObjectMapper mapper=new ObjectMapper(); User user=new User("版本",11,"貓貓"); String str=mapper.writeValueAsString(user); return str; } // 時間資訊傳送 @RequestMapping(value = "j2") public String json02() throws JsonProcessingException { // 獲取json資料格式對映物件 ObjectMapper mapper=new ObjectMapper(); // 關閉時間戳形式輸出時間 mapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS,false); // 自定義時間輸出格式 SimpleDateFormat format=new SimpleDateFormat("yyyy--MM--dd**HH-mm-ss"); // 設定json輸出格式為自定義格式 mapper.setDateFormat(format); Date date=new Date(); // 輸出時間資訊 return mapper.writeValueAsString(date); } // 集合資訊傳送 @RequestMapping(value = "j3") public String json03() throws JsonProcessingException { ObjectMapper mapper=new ObjectMapper(); User user=new User("版本",11,"貓貓"); User use2=new User("版本",11,"貓貓"); User use3=new User("版本",11,"貓貓"); User use4=new User("版本",11,"貓貓"); List<User> users=new ArrayList(); users.add(use2); users.add(use3); users.add(use4); users.add(user); String str=mapper.writeValueAsString(users); return str; } }
前端效果"2022--06--01**20-18-22"
{"userName":"版本","age":11,"description":"貓貓"}
[{"userName":"版本","age":11,"description":"貓貓"},{"userName":"版本","age":11,"description":"貓貓"},{"userName":"版本","age":11,"description":"貓貓"},{"userName":"版本","age":11,"description":"貓貓"}]