Skip to content
Advertisement

QUARKUS – MicroProfile REST Client: add a custom, not mapped field

I am following this article https://quarkus.io/guides/rest-client to build a REST Client to parse the output from the restcountries.eu service. Here the class holding the model:

public class Country {

    public String name;
    public String alpha2Code;
    public String capital;
    public List<Currency> currencies;

    public static class Currency {
        public String code;
        public String name;
        public String symbol;
    }
}

Now, suppose I would like to add a custom fields such as timestamp, to record the instant when this object has been created. I imagine, I would go ahead and add another field like below:

 public class Country {
    
        public String name;
        public String alpha2Code;
        public String capital;
        public List<Currency> currencies;
        public Instant timestamp;  //<--------- added attribute
       [....]

My question is: how do I tell the client to populate that field? Normally, I would have done it in the constructor. However, I could not find docs that explain this part.

Thanks for your help

Simone

Advertisement

Answer

You can actually do this in the default constructor. Frameworks like JSONB or Jackson expect POJOs to have a default constructor. They will call it when they create an instance of Country.

Use the @JsonbTransient or @JsonIgnore annotations to mark that attribute of your POJO as ignorable in order to avoid the unmarshaller complaining about attributes that cannot be found in the response.

 @Data
 public class Country {
    
        private String name;
        private String alpha2Code;
        private String capital;
        private List<Currency> currencies;
        @JsonbTransient // if you're using JSONB (default in Quarkus)
        @JsonIgnore // if you're using Jackson
        private Instant timestamp;

        public Country() {
            this.timestamp = Instant.now();
        }

PS The @Data annotation is something you should consider using. Encapsulation is not a bad thing but creating getters/setters is tedious. But Project Lombok certainly helps here.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement