Home > Net >  Serializing JSON object containing nested objects with dynamic property names with Jackson
Serializing JSON object containing nested objects with dynamic property names with Jackson

Time:01-22

I have been struggling with this the whole day, and I can't seem to get it right. I have a Java Spring Boot project and I need to create an API that returns the following JSON in what I called AggregatedResponse:

  {
    "shipments": {
      "987654321": ["BOX", "BOX", "PALLET"]
    },
    "track": {
      "123456789": "COLLECTING"
    },
    "pricing": {
      "NL": 14.242090605778
      "CN": 20.503467806384
    }
}

Each of the objects (shipments, track, pricing) need to be fetched from an external API. This means that I need to create the AggregatedResponse and use a setter whenever I'm receiving the different data from the external APIs.

The number in the shipments (987654321) comes from the request param passed to the external API that retrieves shipments. The track number (123456789) also comes from an external API.

This is the Java structure I have so far:

public class AggregatedResponse {
    private TrackResponse tracking;
    private ShipmentsResponse shipments;
    private PricingResponse pricing;

    public ShipmentsResponse getShipments() {
        return shipments;
    }

    public void setShipmentsResponse(ShipmentsResponse value) {
        this.shipments = value;
    }

    public TrackResponse getTrackResponse() {
        return tracking;
    }

    public void setTrackResponse(TrackResponse trackResponse) {
        this.tracking = trackResponse;
    }

    public PricingResponse getPricing() {
        return pricing;
    }

    public void setPricing(PricingResponse value) {
        this.pricing = value;
    }
}

The problem I have is that like I mentioned, the shipments and track JSON object have dynamic names, so I have tried different strategies for creating the TrackResponse and the ShipmentsResponse.

How could I do this?

Thanks a lot in advance!

CodePudding user response:

Create a Map from the data instead of class so you can define the keys and serialize it.

  • Related