Home > Mobile >  Is there any way to manipulate json response in spring boot?
Is there any way to manipulate json response in spring boot?

Time:09-24

My project is about a shopping application build with Spring boot. When I get the shopping cart from the endpoint. It will return JSON like this

    {
    "shoppingCartCode": 2,
    "productDetailList": [
        {
            "productDetailCode": 5,
            "price": 21000.0,
            "dateManufacture": "2021-09-23",
            "quantity": 10,
            "colorName": "Pink",
            "warranty": 2,
            "product": {
                "prodCode": 2,
                "prodName": "Z Flod 10",
                "description": "Z Flod  10 Flippable then Break up",
                "brand": {
                    "brandName": "Samsung",
                    "imageList": []
                },
                "shop": {
                    "shopCode": 5,
                    "shopName": "Montri Phone",
                    "shopDescription": "Strict security",
                    "type": "SELLER",
                    "imageList": []
                }
            },
            "imageList": [
                {
                    "imageName": "i-agree.png"
                },
                {
                    "imageName": "i-agree1.png"
                },
                {
                    "imageName": "i-agree2.png"
                },
                {
                    "imageName": "i-agree3.png"
                }
            ]
        }
    ]
}

I want to manipulate the imageList to like this

"imageList": ["i-agree.png","i-agree1.png","i-agree2.png","i-agree3.png"]

Is there any way to manipulate JSON before response?
or it might need POJO to wrap it up before response again?

CodePudding user response:

You can achieve this with a custom serializer as follows:

public class ImageListConverter extends StdConverter<List<Image>, List<String>> {
    @Override
    public List<String> convert(List<Image> images) {
        return images.stream().map(User::getImageName).collect(Collectors.toList());
    }
}

Now you just need to annotate the imageList property:

public class ProductDetail {
    @JsonSerialize(converter = ImageListConverter.class)
    List<Image> imageList;
}

The other option would be changing List<Image> to List<String> and do the conversion when creating ProductDetail. It really depends on how you use ProductDetail elsewhere.

  • Related