Home > Enterprise >  Can I Create a Java 17 Record From a JSON Payload With a Dynamic Field?
Can I Create a Java 17 Record From a JSON Payload With a Dynamic Field?

Time:10-05

I am receiving a JSON payload with a dynamic field but I need to turn it into a Record. Is there a way to do that with a dynamic field? The field in question is under 'Items': "CABC00033003", "CABC00033002", "CABC00033001"

Payload

{
    "Timestamp": "2022-09-15T08:35:15",
    "Agent": "JP",
    "AgentDevice": "",
    "Trace": "LOAD FOR DELIVERY",
    "Consignment": "CABC00033",
    "Items": {
        "CABC00033003": {
            "Type": "CONSIGNMENT",
            "Identifier": ""
        },
        "CABC00033002": {
            "Type": "CONSIGNMENT",
            "Identifier": ""
        },
        "CABC00033001": {
            "Type": "CONSIGNMENT",
            "Identifier": ""
        }
    },
    "FreightHandler": "",
    "Signature": "",
    "Comment": "",
    "Depot": null
}

This is the Method to accept a JSON Payload -> Record

public record CarrierABCStatusUpdateRecord(@JsonProperty("Timestamp") String timeStamp,
                                         @JsonProperty("Agent") String agent,
                                         @JsonProperty("AgentDevice") String agentDevice,
                                         @JsonProperty("Trace") String trace,
                                         @JsonProperty("Consignment") String consignment,
                                         @JsonProperty("Items") String items,
                                         @JsonProperty("FreightHandler") String freightHandler,
                                         @JsonProperty("Signature") String signature,
                                         @JsonProperty("Comment") String comment,
                                         @JsonProperty("Depot") String depot) {}

CodePudding user response:

You can use Map instead of String like this.

public record TypeIdentifier(
    @JsonProperty("Type") String type,
    @JsonProperty("Identifier") String identifier) {
}

public record CarrierABCStatusUpdateRecord(
    @JsonProperty("Timestamp") String timeStamp,
    @JsonProperty("Agent") String agent,
    @JsonProperty("AgentDevice") String agentDevice,
    @JsonProperty("Trace") String trace,
    @JsonProperty("Consignment") String consignment,
//  @JsonProperty("Items") String items,
    @JsonProperty("Items") Map<String, TypeIdentifier> items,
    @JsonProperty("FreightHandler") String freightHandler,
    @JsonProperty("Signature") String signature,
    @JsonProperty("Comment") String comment,
    @JsonProperty("Depot") String depot) {
}
  • Related