Generate constant tags using Xstream in Java

Asked

Viewed 90 times

1

Hello I need to generate an xml with uppercase tags that would necessarily have to be final attributes in the model class to generate xml.

To do this, I’m trying to use the Java Xstream API.

However being these final tags I can not generate, a constructor or create your sets, because they are private?

Is there any way I can solve with Xstream itself or would be better other Java API to solve the problem?

Here’s the class model I’d need. If I leave the attributes unfinished, it would be strange to require my xml tags to be uppercase?

public class Metadados {
  private final String NOME_USUARIO;
  private final String IDADE_USUARIO;
  private final String NUMERO_PROTOCOLO;
}

My XML would need to come out like this:

<NOME_USUARIO>Paulo</NOME_USUARIO>
<COD_USUARIO>36</COD_USUARIO>
<COD_PROTOCOLO>20170111092247</COD_PROTOCOLO>

1 answer

0


An option to not need to declare your attributes in uppercase letter and with final access modifier, would be to use the annotation @XStreamAlias("nome do atributo").

Example:

@XStreamAlias("NOME_USUARIO")
private String nomeUsuario;

See more on documentation.


If the attribute needs to be necessarily final, it makes no sense to have a setter because the "end" access modifier indicates that the value of your attribute cannot be changed after initializing.

@XStreamAlias("metadados")
public class Metadados {

    private final String NOME_USUARIO;
    private final String IDADE_USUARIO;
    private final String NUMERO_PROTOCOLO;

    public Metadados(String NOME_USUARIO, String IDADE_USUARIO, String NUMERO_PROTOCOLO) {
        this.NOME_USUARIO = NOME_USUARIO;
        this.IDADE_USUARIO = IDADE_USUARIO;
        this.NUMERO_PROTOCOLO = NUMERO_PROTOCOLO;
    }

    public String getNOME_USUARIO() {
        return NOME_USUARIO;
    }

    public String getIDADE_USUARIO() {
        return IDADE_USUARIO;
    }

    public String getNUMERO_PROTOCOLO() {
        return NUMERO_PROTOCOLO;
    }
}

Generating xml with Xstream:

XStream xstream = new XStream(new DomDriver("UTF8", new NoNameCoder()));
xstream.processAnnotations(Metadados.class);
String xml = xstream.toXML(new Metadados("nome", "20", "123456"));
System.out.println(xml);

Upshot:

<metadados>
    <NOME_USUARIO>nome</NOME_USUARIO>
    <IDADE_USUARIO>20</IDADE_USUARIO>
    <NUMERO_PROTOCOLO>123456</NUMERO_PROTOCOLO>
</metadados>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.