![](/img/trans.png)
[英]how to create json response in spring boot java like this as shown when the following attributes are not present in json request
[英]How to create a parent child Json response in Spring Boot with a Enum using Java
我正在尝试从 Spring 引导应用程序创建一个 json 响应,其中枚举的名称将是父结构,并且所有子结构都将居住在该名称之下。 我创建的只是显示子层次结构,但我也想要父级。就像我想要的下面
items: [
{
title: "ABC ",
subTitle: "",
description:
"123 ",
url: "",
},
{
title: "Revenue",
subTitle: "",
description:
"Digitally ",
url: "",
},
{
title: "xyz",
subTitle: "",
description:
"345,",
url: "stackoverflow.com",
},
{
title: "kji",
subTitle: "",
description:
"890",
url: "",
},
{
title: "KOI",
subTitle: "",
description:
"054,",
url: "",
},
]
我得到的是
[
{
title: "ABC ",
subTitle: "",
description:
"123 ",
url: "",
},
{
title: "Revenue",
subTitle: "",
description:
"Digitally ",
url: "",
},
{
title: "xyz",
subTitle: "",
description:
"345,",
url: "stackoverflow.com",
},
{
title: "kji",
subTitle: "",
description:
"890",
url: "",
},
{
title: "KOI",
subTitle: "",
description:
"054,",
url: "",
},
]
以下是我使用过的代码
import java.util.Arrays;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EnumController {
@GetMapping("/getEnumResponse")
public List<TreeEnum> getCurrentContent() {
MyData mData = new MyData ();
return Arrays.asList(TreeEnum.values());
}
}
import com.fasterxml.jackson.annotation.JsonFormat;
@JsonFormat(shape=JsonFormat.Shape.OBJECT)
public enum TreeEnum {
VALUE1 ("Pay","","Digitally.",""),
VALUE2 ("Revenue","","enable",""),
VALUE3("Banking","","Treasury Reporting etc","CHOICE"),
VALUE4("Accounting","","Corporate","");
private String title;
private String subTitle;
private String url;
private String description;
Response(String title,String subTitle,String description,String url) {
this.title = title;
this.subTitle = subTitle;
this.description = description;
this.url = url;
}
public String getTitle() {
return title;
}
public String getSubTitle() {
return subTitle;
}
public String getUrl() {
return url;
}
public String getDescription() {
return description;
}
}
import java.util.List;
public class MyData {
private List<TreeEnum > responses;
public List<TreeEnum > getResponses() {
return responses;
}
public void setResponses(List<Response> responses) {
this.responses = responses;
}
}
您正在返回项目的集合,您需要返回 object 以及包含 collections 的属性项目。
这可以通过 Map 来实现。
@GetMapping("/getEnumResponse")
public Map getCurrentContent() {
Map response = new HashMap();
response.put("items", TreeEnum.values());
return response;
}
如果您使用的是 Java9 或更高版本,您可以这样做
@GetMapping("/getEnumResponse")
public Map getCurrentContent() {
return Map.of("items", TreeEnum.values());
}
创建一个 ItemDto 并在其中传递 TreeEnum 列表。 你也可以使用 @JsonRootName("Item") 如果你不想列出并在你的映射中启用根值 mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.