How does the backend java return JSON data to the frontend
JSON data
var data = [
{
checkinginTime: '2023-04-23',
ip: '111'
},
{
checkinginTime: '2023-04-22',
ip: '111'
},
{
checkinginTime: '2023-04-28',
ip: '111'
},
{
checkinginTime: '2023-04-24',
ip: '111'
}
];
Backend returns
在Java后端中,你可以使用Spring框架提供的@ResponseBody注解将Java对象转换为JSON格式的数据,并返回给前端。以下是一个示例代码,它将一个Java List对象转换为JSON格式的数据,并返回给前端:
```javaimport org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;
@Controllerpublic class MyController {
@RequestMapping("/getJsonData")
@ResponseBody public List<User> getJsonData() {
// 创建一个List对象
List<User> userList = new ArrayList<>();
// 添加一些用户数据 userList.add(new User("张三", 18));
userList.add(new User("李四", 20));
userList.add(new User("王五", 22));
// 返回List对象,Spring会自动将其转换为JSON格式的数据 return userList;
}
// 定义一个User类,用于测试 public static class User {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
}
In the above code, the @ResponseBody annotation is used to convert the Java List object into JSON formatted data and return it to the front end. Spring will automatically convert the List object to a JSON-formatted array, where each element is a JSON object. In this example, each JSON object contains a name property and an age property.
Regenerate