[英]Display json in custom format using spring rest
I have a rest controller which returns JSON in some format but I want the JSON output in a different format .To implement the same I am using Spring REST.I have posted all model and controller classes below.My question is what could I do to get my expected response? 我有一个rest控制器,它以某种格式返回JSON,但我想以其他格式返回JSON输出。要实现相同的输出,我正在使用Spring REST。我在下面发布了所有模型和控制器类。我的问题是我该怎么办得到我预期的回应?
ACTUAL JSON 实际JSON
[
{
"name": "CategoryName1",
"sub": [
{
"name": "SubCategory1"
},
{
"name": "SubCategory2"
}
]
},
{
"name": "CategoryName2",
"sub": [
{
"name": "SubCategory3"
},
{
"name": "SubCategory4"
}
]
}
] ]
EXPECTED JSON 预期的JSON
{
"CategoryName1": ["SubCategory1", "SubCategory2"],
"CategoryName2": ["SubCategory1", "SubCategory2"]
}
Category 类别
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;
}
} }
Subcategory 子目录
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;
}
You can try like this : 您可以这样尝试:
public class Category {
private Map<String, List<String>> response = new HashMap<>();
Category(Map<String, List<String>> response){
this.response = response;
}
}
Usage: Fill data with Category object and return from rest api. 用法:使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.