Convert Java object to JSON with Gson (generating with backslash)

1

I'm trying to generate a JSON based on a Java object.

JSON is being generated, but some slashes have been improperly included:

import java.io.Serializable;

import com.google.gson.annotations.SerializedName;

public class Documento implements Serializable{
    private static final long serialVersionUID = 1L;

    @SerializedName("Identificador")
    private String identificador;

    public Documento (){}

    public Documento (String identificador){
        this.identificador = identificador;
    }

    public String getIdentificador() {
        return identificador;
    }

    public void setIdentificador(String identificador) {
        this.identificador = identificador;
    }
}

String identificador = jsonObjResposta.getAsJsonArray("ListaObjetos").iterator().next().getAsJsonObject().get("Identificador").toString();

Documento documento = new Documento(identificador);

System.out.println("gson.toJson(documento): " + gson.toJson(documento));

Output:

gson.toJson(documento): {"Identificador":"\"bene1\""}

    
asked by anonymous 30.11.2018 / 13:00

1 answer

2

I did a basic test with version 2.8.5 of Gson:

Gson gson = new Gson();
Documento documento = new Documento("bene1");

System.out.println("gson.toJson(documento): " + gson.toJson(documento));

The output was left without the quotation marks:

gson.toJson(documento): {"Identificador":"bene1"}

By comments we saw that in fact the String original was coming with the quotation marks, so one solution would be to simply remove them, using replaceAll :

// remove as aspas do identificador
identificador = identificador.replaceAll("\"", "");
    
30.11.2018 / 13:51