型号
public class Organisation {
private String name;
public Organisation() { }
public Organisation(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Controller
@RequestMapping(method = RequestMethod.GET)
public List<Organisation> getAll() {
Organisation organisation = new Organisation("google");
List<Organisation> organisations = new ArrayList<>();
organisations.add(organisation);
return organisations;
}
这将给出如下响应:
[
{
"name": "google"
}
]
如果我们想要这样的东西怎么办:
{
"data": [{
"type": "organisations"
"attributes": {
"name": "google"
}
]
}
那么如何自定义json.我知道 Spring MVC 默认使用 Jackson 将模型转换为 JSON。有没有办法定制它。我正在尝试以 JSONApi 标准发送响应。另外有人可以告诉如何在回复中创建链接
最佳答案
创建类:
public class Object1 {
private List<Object2> data;
public Object1() {
}
public Object1(List<Object2> data) {
this.data = data;
}
//getters and setters
}
public class Object2 {
private String type;
private Object3 attributes;
public Object2() {
}
public Object2(String type, Object3 attributes) {
this.type = type;
this.attributes = attributes;
}
//getters and setters
}
public class Object3 {
private String name;
public Object3(String name) {
this.name = name;
}
public Object3() {
}
//getters and setters
}
现在你的 Controller 方法应该是这样的:
@RequestMapping(method = RequestMethod.GET)
public Object3 getAll() {
List<Object2> data = new ArrayList<>();
data.add(new Object2("organisations", new Object3("google")));
return new Object1(data);
}
关于java - 使用 Spring MVC 自定义 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38810908/