Car*_*eto 4 json annotations spring-boot
是否可以在 Spring Boot 中对 JSON 对象使用 @ Produces ?或者还有另一种方法来实现这一点:
JSONObject J_Session = new JSONObject();
J_Session.put("SESSION_ID_J", session_jid);
J_Session.put("J_APP", "J");
J_Session.put("REST_ID_J", rest_id);
Run Code Online (Sandbox Code Playgroud)
这是一个简单的例子:
RestController类
import java.util.ArrayList;
import java.util.List;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.websystique.springboot.model.User;
@RestController
@RequestMapping("/api")
public class RestApiController {
@RequestMapping(value = "/user/", method = RequestMethod.GET, produces = { "application/json" })
public List<User> listAllUsers() {
List<User> users = new ArrayList<User>();
users.add(new User(1, "Sam", 30, 70000));
users.add(new User(2, "Tom", 40, 50000));
users.add(new User(3, "Jerome", 45, 30000));
users.add(new User(4, "Silvia", 50, 40000));
return users;
}
}
Run Code Online (Sandbox Code Playgroud)
该属性produces = { "application/json" }自动将 List 集合转换为 json 响应。
下面是 POJO 类。
用户Pojo类
public class User {
private long id;
private String name;
private int age;
private double salary;
public User(){
}
public User(long id, String name, int age, double salary){
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
}
Run Code Online (Sandbox Code Playgroud)
JSON 响应示例:
[
{
"id":1,
"name":"Sam",
"age":30,
"salary":70000
},
{
"id":2,
"name":"Tom",
"age":40,
"salary":50000
},
{
"id":3,
"name":"Jerome",
"age":45,
"salary":30000
},
{
"id":4,
"name":"Silvia",
"age":50,
"salary":40000
}
]
Run Code Online (Sandbox Code Playgroud)
请点击此链接获取有关 CRUD 操作的完整详细示例。
上面的代码来自这个链接本身,我只是修改了控制器部分以使其简单。
| 归档时间: |
|
| 查看次数: |
42753 次 |
| 最近记录: |