我有一个休息控制器,它以某种格式返回JSON但我希望JSON输出格式不同。要实现相同的我使用Spring REST。我已经发布了下面的所有模型和控制器类。我的问题是什么可以我是为了得到预期的回应?
ACTUAL 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;
}
}
控制器
@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;
}
答案 0 :(得分:1)
您可以尝试这样:
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);