Search code examples
javajsonspring-bootspring-restcontrollerspring-mybatis

Spring Responsebody, Naming List objects in json


I'm working on a REST service using the Spring Framework's spring-boot library. I'm getting responses from my services as JSON, my problem is I am using a parent class to store all of the objects being sent as the result of a request and the response is sent without names on the JSON array.

This is the output for one of my tests:

success: true,
message: null,
data: [
{ },
{
vehicleBatteryId: 3,
modelTypeId: 3,
cycleCount: -9640,
currentCapacity: -9640,
manufactureDate: 414037682000,
manufacturerId: 10,
modeTypeCode: 461271880,
partStatus: 215692740,
lastMaintenanceDate: 428880743000
},
{
vehicleBmsId: 3,
bmsModelId: 5,
manufactureDate: 942436247000,
manufacturerId: 4,
lastMaintenanceDate: 437823118000,
partStatus: 477293493,
replaceDate: 179716409000,
replaceDistance: 4783810
}...

And this is the Result I'm trying to get:

success: true,
message: null,
data: {
Property1:{ },
Property2:{
vehicleBatteryId: 3,
modelTypeId: 3,
cycleCount: -9640,
currentCapacity: -9640,
manufactureDate: 414037682000,
manufacturerId: 10,
modeTypeCode: 461271880,
partStatus: 215692740,
lastMaintenanceDate: 428880743000
},...

This is the parent class. I want to be able to use it for every response my service creates regardless of the details of that response

public class MasterResponse extends RequestStatus{
    private List<Object> data;

    public MasterResponse() {
        init();
    }

    public MasterResponse(boolean _success, String _message){
        super(_success, _message);
        init();
    }
    private void init(){
        this.data = new ArrayList<Object>();
    }

    public void addModel(Object newModel){
        this.data.add(newModel);
    }

    public void clearData(){
        this.data=null;
    }

    public List<Object> getData() {
        return data;
    }

    public void setData(List<Object> data) {
        this.data = data;
    }
}

Anyone have any ideas? As far as I can tell Spring uses Jackson to convert to json, I'm exploring what I can do with the json view functions they provide at the moment.


Solution

  • You are using an ArrayList, which Jackson serialize as [{...},{...}, ...] You could use a Map (i.e. HashMap<>) for data, but you might need to create a custom "push()" or add() function, in order to maintain the index propery. i.e. Property1.

    the HashMap Object wil be serialised as: data: {"index-1":{...}, "index-2": { ... } ... }

    simple example for your code:

        private Map<String, Object> data;
        int nextIndex = 1;
    
        private void init(){
            this.data = new HashMap<String, Object>();
        }
    
        public void addModel(Object newModel){
                this.data.add("Property" + this.nextIndex, newModel);
                this.nextIndex++;
        }