使用Spring控制器通过json通过HashMap将用户定义的对象作为键传递

时间:2020-04-29 09:32:41

标签: json spring rest hashmap postman

我将返回HashMap<Category,List<Category >>,其中category是用户定义的类。 我已经为Category.class覆盖了hashcode()和equals()方法 我可以作为类别类的对象访问控制器中HashMap的键。 但是当您在POSTMAN中看到结果时,键对象会自动转换为String 谁能告诉我为什么它会自动转换为String? 并建议我一种即使将其转换为JSON

仍将这些键保留为Category Object的方法

邮递员-

{
"Category [categoryId=3, categoryName=Plumbing, parentCategory=null]": [
    {
        "categoryId": 13,
        "categoryName": "Basin and Sink",
        "parentCategory": 3
    },
    {
        "categoryId": 14,
        "categoryName": "Tap & Mixer",
        "parentCategory": 3
    }
],
"Category [categoryId=4, categoryName=Cleaning, parentCategory=null]": [
    {
        "categoryId": 5,
        "categoryName": "Kitchen Cleaning",
        "parentCategory": 4
    },
    {
        "categoryId": 6,
        "categoryName": "Bathroom Cleaning",
        "parentCategory": 4
    },
    {
        "categoryId": 7,
        "categoryName": "Deep home cleaning",
        "parentCategory": 4
    }
]
}

控制器:-

@GetMapping("/getAllCategoriesMap")
public HashMap<Category,List<Category >> getAllCategoriesMap() {
    try {
        HashMap<Category,List<Category >> c=categoryService.getAllCategoriesMap();
        System.out.println(c.toString());
        for (Category key : c.keySet()) {
              System.out.println(key.toString()); 
        }
        return c;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

控制器中系统输出的输出-

{Category [categoryId=3, categoryName=Plumbing, parentCategory=null]=[Category [categoryId=13, categoryName=Basin and Sink, parentCategory=3], Category [categoryId=14, categoryName=Tap & Mixer, parentCategory=3]], Category [categoryId=4, categoryName=Cleaning, parentCategory=null]=[Category [categoryId=5, categoryName=Kitchen Cleaning, parentCategory=4], Category [categoryId=6, categoryName=Bathroom Cleaning, parentCategory=4], Category [categoryId=7, categoryName=Deep home cleaning, parentCategory=4]], Category [categoryId=8, categoryName=Electrician, parentCategory=null]=[Category [categoryId=15, categoryName=Switch & Socket, parentCategory=8]], Category [categoryId=9, categoryName=Refrigerator, parentCategory=null]=[Category [categoryId=10, categoryName=Laptop repair, parentCategory=9], Category [categoryId=16, categoryName=Installation, parentCategory=9]], Category [categoryId=11, categoryName=Aqua Guard, parentCategory=null]=[Category [categoryId=12, categoryName=CLeaning aqua, parentCategory=11]]}



Category [categoryId=3, categoryName=Plumbing, parentCategory=null]
Category [categoryId=4, categoryName=Cleaning, parentCategory=null]
Category [categoryId=8, categoryName=Electrician, parentCategory=null]
Category [categoryId=9, categoryName=Refrigerator, parentCategory=null]
Category [categoryId=11, categoryName=Aqua Guard, parentCategory=null]

0 个答案:

没有答案
相关问题