Map String to Object using Jackson with inheritance

FearX :

I have the QueueContent class that it has is a superclass of two others.

I get a String in JSON format that contains the information I need to extract. The super class is:

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class QueueContent {

    private String empresa;
    private String empresa_cor;
    private String empresa_contato;
    private String empresa_url;
    private String empresa_telefone;
    private String empresa_idioma;

    public QueueContent(String empresa, String empresa_cor, String empresa_contato, String empresa_url, String empresa_telefone, String empresa_idioma) {
        this.empresa = empresa;
        this.empresa_cor = empresa_cor;
        this.empresa_contato = empresa_contato;
        this.empresa_url = empresa_url;
        this.empresa_telefone = empresa_telefone;
        this.empresa_idioma = empresa_idioma;
    }

    public QueueContent() {
    }
}

I'm using Lombok to generate Getters / Setters)

This is the child class:

@Data
public class EmailCameraOffline extends  QueueContent {
    private Timestamp camera_last_online;
    private String camera_nome;
    private String empresa_url_plataforma;

    public EmailCameraOffline(String empresa, String empresa_cor, String empresa_contato, String empresa_url, String empresa_telefone, String empresa_idioma, Timestamp camera_last_online, String camera_nome, String empresa_url_plataforma) {
        super(empresa, empresa_cor, empresa_contato, empresa_url, empresa_telefone, empresa_idioma);
        this.camera_last_online = camera_last_online;
        this.camera_nome = camera_nome;
        this.empresa_url_plataforma = empresa_url_plataforma;
    }

    public EmailCameraOffline() {
    }
}

So I've done:

 EmailCameraOffline infosEmail = new ObjectMapper().readValue(content, EmailCameraOffline.class);
                System.out.println(infosEmail);

And the output is:

 EmailCameraOffline (camera_last_online = 2020-03-12 03: 01: 45.0, camera_nome = Pier Cam 1, empresa_url_platform = null)

How do I get my EmailCameraOffline object to have the superclass attributes initialized?

hradecek :

Everything should be loaded and initialized just fine, so calling:

System.out.println(infosEmail.getEmpresa());

should give expected value.

Problem

The problem is in the default implementation of toString() method (done via @Data) at EmailCameraOffline class, which does not include inherited fields.

Solution

To fix this you can "override" @Data's toString() implementation to include inherited fields as well using Lombok as:

@Data
@ToString(callSuper = true)
public class EmailCameraOffline extends QueueContent {
...
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=317834&siteId=1