gpt4 book ai didi

java - 使用 spring Rest 以自定义格式显示 json

转载 作者:行者123 更新时间:2023-12-02 11:32:07 26 4
gpt4 key购买 nike

我有一个休息 Controller ,它以某种格式返回 JSON,但我想要不同格式的 JSON 输出。为了实现相同的功能,我使用 Spring REST。我在下面发布了所有模型和 Controller 类。我的问题是什么可以我这样做是为了得到我预期的回应吗?

实际 JSON

[
{
"name": "CategoryName1",
"sub": [
{
"name": "SubCategory1"
},
{
"name": "SubCategory2"
}
]
},
{
"name": "CategoryName2",
"sub": [
{
"name": "SubCategory3"
},
{
"name": "SubCategory4"
}
]
}

]

预期的 JSON

{
"CategoryName1": ["SubCategory1", "SubCategory2"],
"CategoryName2": ["SubCategory1", "SubCategory2"]
}

类别

public class Category{

public String name;
public List<Subcategory> sub;
public List<Subcategory> getSub() {
return sub;
}

public void setSub(List<Subcategory> sub) {
this.sub = sub;
}

public Category(String name) {
super();
this.name = name;
}

}

子类别

public class Subcategory{

public String name;

public Subcategory(String name) {
super();
this.name = name;
}

}

Controller

@RequestMapping(value = "/dropdown", method = RequestMethod.GET, produces = "application/json")
public @ResponseBody List<Category> dropdown() {
Subcategory SubCategory1 = new Subcategory("SubCategory1");
Subcategory SubCategory2 = new Subcategory("SubCategory2");
Subcategory SubCategory3 = new Subcategory("SubCategory3");
Subcategory SubCategory4 = new Subcategory("SubCategory4");

Category CategoryName1 = new Category("CategoryName1");
Category CategoryName2 = new Category("CategoryName2");

List<Subcategory> subList = new ArrayList<Subcategory>();
subList.add(SubCategory1);
subList.add(SubCategory2);
List<Subcategory> subList2 = new ArrayList<Subcategory>();
subList2.add(SubCategory3);
subList2.add(SubCategory4);

CategoryName1.setSub(subList);
CategoryName2.setSub(subList2);

List<Category> cat = new ArrayList<Category>();
cat.add(CategoryName1);
cat.add(CategoryName2);

return cat;
}

最佳答案

你可以这样尝试:

public class Category {
private Map<String, List<String>> response = new HashMap<>();
Category(Map<String, List<String>> response){
this.response = response;
}
}

用法:用Category对象填充数据并从rest api返回。

private Map<String, List<String>> response = new HashMap<>();
List<String> list = new ArrayList<>();
list.add("SubCategory1");
list.add("SubCategory2");
response.put("CategoryName1", list);
response.put("CategoryName2", list);
Category category = new Category(response);

关于java - 使用 spring Rest 以自定义格式显示 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49220216/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com