Search code examples
javajsonbuilder

Builder Pattern and Json alias name


I want to construct the builder object for the below class

@Value
@Builder
public static class Input {
    String name;
    Source source;
}

@Value
@Builder
public static class Source {
    //@JsonAlias({"metric", state"})
    //@JsonProperty("state")
    Metric metric ;
}

@Value
@Builder
public static class Metric {
    String ref;
}

I want to construct the objects like

Input.builder()
        .name("state")
        .source(Source.builder()
            .metric(Metric.builder()
                .ref("ref")
                .build())
            .build())
        .build()

At the same time , the 'metric' name will be changed like 'state' in one of the scenarios,

Input.builder()
        .name("state")
        .source(Source.builder()
            .state(Metric.builder()
                .ref("ref")
                .build())
            .build())
        .build()

Constructing the objects differ only in the name of metric / state. The structure remains same. I tried with @JsonAlias and not finding it helpful. Can anyone give me the correct reference or how to use the different name in builder pattern when the structure is same?


Solution

  • you need to tell lombok what is the name of the field you want in a constructor and annotate with @Builder. see the following code and static class Metric

    import lombok.Builder;
    import lombok.Value;
    
    public class Test {
    
    @Value
    @Builder
    public static class Input {
        String name;
        Source source;
    }
    
    @Value
    public static class Source {
        Metric metric ;
        
        @Builder
        public Source(Metric state, Metric metric) {
            this.metric = state != null ? state : metric;
        }
    }
    
    @Value
    @Builder
    public static class Metric {
        String ref;
    }
    
    public static void main(String... args) {
        Input.builder()
                .name("state")
                .source(Source.builder()
                        .state(Metric.builder()
                                .ref("ref")
                                .build())
                        .build())
                .build();
           
           Input.builder()
                .name("state")
                .source(Source.builder()
                        .metric(Metric.builder()
                                .ref("ref")
                                .build())
                        .build())
                .build();
        }
    }