Map dynamic keys to bean and convert to snake case

Viewed 94

I have the following json response from a REST call which I have no control over. Thus need to work with this.

{
    "main": {
        "productOne": {
            "randomData": {
                "summaryData": {
                    "title": "title 1",
                    "subTitle": "title 1"
                },
                "creditData": {
                    "title": "title 3",
                    "subTitle": "title 1"
                },
                "altData": {
                    "title": "title 4",
                    "subTitle": "title 1"
                }
            }
        },
        "productTwo": {
            "fixedData": {
                "summaryData": {
                    "title": "title 5",
                    "subTitle": "title 1"
                },
                "creditData": {
                    "title": "title 6",
                    "subTitle": "title 1"
                }
            }
        }
    }
}

I am trying to match these values to multiple beans to follow this same json format.
>For example, I could match the "main" key fine cos that occurs only once and it would always come up as main.
Thus I could map it something like following and this works.

@Getter
@Setter
@JsonInclude(Include.NON_NULL)
public class MainData {
    @JsonProperty("main")
    private Main main;
}

@Getter
@Builder
@JsonDeserialize(builder = Main.MainBuilder.class)
public class Main {
    // this needs to be dynamic, can't hard code productOne.
    @JsonProperty("productOne")
    private final Product productOne;
}

@Getter
@Builder
@JsonInclude(Include.NON_NULL)
@JsonDeserialize(builder = Product.ProductBuilder.class)
public class Product {
    // ok to look for randomData. This doesn't need to be dynamic.
    @JsonProperty("randomData")
    private final Map<String, Benefit> randomData; 
}

@Getter
@Setter
@JsonInclude(Include.NON_NULL)
public class Benefit {  
    private String title;
    private String subTitle;
}

But there is an issue with this cos I am trying to match productOne.
This is a dynamic value in the json format as seen above thus this could have been
productOne or productTwo or anythingElse.

How could I map this dynamically in this case?
On top of mapping this, I am looking to make it snake case cos I am taking this format and
sending it as a response to my client (along with many other data not relevanrt here).

Thus when I send it to my client, the response should be like following:

{
    "product_one": {
        "random_data": {
            "summary_data": {
                "title": "title 6",
                "sub_title": "title 1"
             }
         }
    }
}

To reiterate the query, how can I make the keys dynamic for the portions productOne & productTwo
plus is there a way can I make them snake case right as I capture these values in my beans? Thanks.

0 Answers
Related