【问题标题】:Display json in custom format using spring rest使用spring rest以自定义格式显示json
【发布时间】:2023-03-10 20:14:01
【问题描述】:

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

实际 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;
}

【问题讨论】:

    标签: java json spring rest spring-mvc


    【解决方案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);
    

    【讨论】:

      猜你喜欢
      • 2019-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-24
      • 1970-01-01
      • 1970-01-01
      • 2020-11-09
      • 2017-12-15
      相关资源
      最近更新 更多