Problem to convert JSON to JAVA object

2

I have the following JSON , it is a response of API :

    {  
   "ES1800496542831234567890":{ "transactions":[  
         {  
            "idmovimiento":"714597",
            "fechaoperacion":"2016-05-27",
            "fechavalor":"2016-05-27",
            "descripcion":"descripcion 2",
            "importe":"-1431.43",
            "saldo":"0.00",
            "orden":"2",
            "oficinaorigen":"0901",
            "conceptocomun":"03",
            "conceptopropio":"227",
            "documento":"0000000000",
            "referencia1":"B50574300000",
            "referencia2":"2222222222222222",
            "newreferencia1":"",
            "newreferencia2":"",
            "facturas":"0",
            "documentos":"0",
            "additional":[  
               {  
                  "numcomplementario":"1",
                  "concepto1":"COR1Schindler Espana S.A. ",
                  "concepto2":" "
               },
               {  
                  "numcomplementario":"2",
                  "concepto1":"ES17501A50001726 000",
                  "concepto2":"000007275 "
               },
               {  
                  "numcomplementario":"3",
                  "concepto1":"OTHR Mas detalles de su factura en ",
                  "concepto2":"www.schindler.es FACTURA 3472855286 N"
               },
               {  
                  "numcomplementario":"4",
                  "concepto1":"IF-CIF ESE50110303 RECIBO 48317499\/2",
                  "concepto2":"314048 VTO 28-05-16 "
               },
               {  
                  "numcomplementario":"5",
                  "concepto1":"190000483174992016 0002314048 5 ",
                  "concepto2":" 20150415false "
               }
            ]
         },
         {  
            "idmovimiento":"714596",
            "fechaoperacion":"2016-05-27",
            "fechavalor":"2016-05-27",
            "descripcion":"descripcion editada",
            "importe":"-1431.43",
            "saldo":"1.00",
            "orden":"1",
            "oficinaorigen":"0901",
            "conceptocomun":"03",
            "conceptopropio":"227",
            "documento":"0000000000",
            "referencia1":"B50574300000",
            "referencia2":"E50110303 ",
            "newreferencia1":"111111111111",
            "newreferencia2":"222222222222222",
            "facturas":"1",
            "documentos":"0"
         }
      ]
   }
}

I have created the following Classes JAVA :

    public class Respuesta {

    private String error;
    private List<Cuenta> cuentas;

    public List<Cuenta> getCuentas() {
        return cuentas;
    }

    public void setCuentas(List<Cuenta> cuentas) {
        this.cuentas = cuentas;
    }

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }
}

    public class Cuenta {

    private String iban;
    private Transactions transactions;

    public String getIban() {
        return iban;
    }

    public void setIban(String iban) {
        this.iban = iban;
    }

    public Transactions getTransactions() {
        return transactions;
    }

    public void setTransactions(Transactions transactions) {
        this.transactions = transactions;
    }
}

    public class Transactions {

    private List<Movimientos> movimientos;

    public List<Movimientos> getMovimientos() {
        return movimientos;
    }

    public void setMovimientos(List<Movimientos> movimientos) {
        this.movimientos = movimientos;
    }
}

    public class Movimientos {

    private Long idmovimiento;
    private Date fechaoperacion;
    private Date fechavalor;
    private String descripcion;
    private BigDecimal importe;
    private BigDecimal saldo;
    private Integer orden;
    private String oficinaorigen;
    private String conceptocomun;
    private String conceptoPropio;
    private String documento;
    private String referencia1;
    private String referencia2;
    private String newreferencia1;
    private String newreferencia2;
    private int facturas;
    private int documentos;
    private List<Additional> additional;

    public String getConceptoPropio() {
        return conceptoPropio;
    }

    public void setConceptoPropio(String conceptoPropio) {
        this.conceptoPropio = conceptoPropio;
    }

    public Long getIdmovimiento() {
        return idmovimiento;
    }

    public void setIdmovimiento(Long idmovimiento) {
        this.idmovimiento = idmovimiento;
    }

    public Date getFechaoperacion() {
        return fechaoperacion;
    }

    public void setFechaoperacion(Date fechaoperacion) {
        this.fechaoperacion = fechaoperacion;
    }

    public Date getFechavalor() {
        return fechavalor;
    }

    public void setFechavalor(Date fechavalor) {
        this.fechavalor = fechavalor;
    }

    public String getDescripcion() {
        return descripcion;
    }

    public void setDescripcion(String descripcion) {
        this.descripcion = descripcion;
    }

    public BigDecimal getImporte() {
        return importe;
    }

    public void setImporte(BigDecimal importe) {
        this.importe = importe;
    }

    public BigDecimal getSaldo() {
        return saldo;
    }

    public void setSaldo(BigDecimal saldo) {
        this.saldo = saldo;
    }

    public Integer getOrden() {
        return orden;
    }

    public void setOrden(Integer orden) {
        this.orden = orden;
    }

    public String getOficinaorigen() {
        return oficinaorigen;
    }

    public void setOficinaorigen(String oficinaorigen) {
        this.oficinaorigen = oficinaorigen;
    }

    public String getConceptocomun() {
        return conceptocomun;
    }

    public void setConceptocomun(String conceptocomun) {
        this.conceptocomun = conceptocomun;
    }

    public String getDocumento() {
        return documento;
    }

    public void setDocumento(String documento) {
        this.documento = documento;
    }

    public String getReferencia1() {
        return referencia1;
    }

    public void setReferencia1(String referencia1) {
        this.referencia1 = referencia1;
    }

    public String getReferencia2() {
        return referencia2;
    }

    public void setReferencia2(String referencia2) {
        this.referencia2 = referencia2;
    }

    public String getNewreferencia1() {
        return newreferencia1;
    }

    public void setNewreferencia1(String newreferencia1) {
        this.newreferencia1 = newreferencia1;
    }

    public String getNewreferencia2() {
        return newreferencia2;
    }

    public void setNewreferencia2(String newreferencia2) {
        this.newreferencia2 = newreferencia2;
    }

    public int getFacturas() {
        return facturas;
    }

    public void setFacturas(int facturas) {
        this.facturas = facturas;
    }

    public int getDocumentos() {
        return documentos;
    }

    public void setDocumentos(int documentos) {
        this.documentos = documentos;
    }

    public List<Additional> getAdditional() {
        return additional;
    }

    public void setAdditional(List<Additional> additional) {
        this.additional = additional;
    }
}

    public class Additional {

    private String numComplementario;
    private String concepto1;
    private String concepto2;

    public String getNumComplementario() {
        return numComplementario;
    }

    public void setNumComplementario(String numComplementario) {
        this.numComplementario = numComplementario;
    }

    public String getConcepto1() {
        return concepto1;
    }

    public void setConcepto1(String concepto1) {
        this.concepto1 = concepto1;
    }

    public String getConcepto2() {
        return concepto2;
    }

    public void setConcepto2(String concepto2) {
        this.concepto2 = concepto2;
    }
}

But when I try to convert the JSON to the JAVA object, the attributes are empty. Is not the JAVA structure that I have set up correct? Which one would be correct?

    
asked by Enrique Rodrigo Alejandro 10.10.2016 в 21:44
source

7 answers

0

The problem you have is that for gson to do his "Magic" all the variables have to have his name well defined.

Your problem is that the account number that you want to extract, comes on the Json as if it were the name of a Field.

I would solve it in the following way:

First add these dependencies:

<dependency>
       <groupId>org.json</groupId>
       <artifactId>json</artifactId>
       <version> LATEST</version>
</dependency>
<dependency>
       <groupId>com.google.code.gson</groupId>
       <artifactId>gson</artifactId>
       <version>2.7</version>
</dependency>

the classes you created would leave them the same (only the "Answer" class did not use it).

And when converting the Json do this:

import org.json.JSONObject;
import com.google.gson.Gson;



    JSONObject obj = new JSONObject(jsonData);
    Set<String> st = obj.keySet();
    Cuenta cuenta = new Cuenta();
    cuenta.setIban(st.toArray()[0].toString());
    Gson gson = new Gson();
    Movimientos[] movs = gson.fromJson(obj.getJSONObject(st.toArray()[0].toString()).getJSONArray("transactions").toString(),Movimientos[].class);
    Transactions transactions = new Transactions();
    transactions.setMovimientos(new ArrayList<Movimientos>(Arrays.asList(movs)));
    cuenta.setTransactions(transactions);
    System.out.println(cuenta.toString());

jsonData is a String with all the answer.

With this you create UNA account with the IBAN and the Transactions.

I hope it serves you! greetings .-

    
answered by 12.10.2016 / 18:01
source
1

The code to perform the conversion is this:

AgrFinanciero mvtos = gson.fromJson(jsonMovimientos, AgrFinanciero.class);

The variable jsonMovimientos contains the answer obtained in the call.

    
answered by 11.10.2016 в 07:46
0

The code:

AgrFinanciero mvtos = gson.fromJson(jsonMovimientos, AgrFinanciero.class);

It is correct, however, it is necessary to mention that you must include the gSon reference to your java project. Have you already done it?

    
answered by 11.10.2016 в 23:03
0

In order for GSON to know how to convert the JSON into an object, it must know what correspondence there is between the values and the attributes of the objects.

Usually the name of the field is provided, ie with

{"nombre":"Jhon Wayne"}

GSON (or Jackson) know how to do

setNombre("Jhon Wayne")

normal attributes such as values, arrays as lists, etc. they will do it automatically if the name of the property in your bean corresponds to the one with the JSON

But oh dear

The JSON that you pass has an attribute  ES1800496542831234567890 that surely is variable (the correct thing would be that they had defined it as "id": "ES1800496542831234567890" and then "data": {.... the rest ....}

ergo, it's going to touch you to work on a serializer by hand since GSON will not know how to turn it into a single one

You can try to use a map "bareback" instead of the business object, it's a can but it will work

Map<String,Object> result = gson.fromJson(jsonMovimientos,HashMap.class);
    
answered by 12.10.2016 в 21:06
0

You can use this page link to create your models.

In your case it would be the following:

public class Additional {

    @SerializedName("numcomplementario")
    @Expose
    public String numcomplementario;
    @SerializedName("concepto1")
    @Expose
    public String concepto1;
    @SerializedName("concepto2")
    @Expose
    public String concepto2;

}

public class ES1800496542831234567890 {

    @SerializedName("transactions")
    @Expose
    public List<Transaction> transactions = new ArrayList<Transaction>();

}

public class Example {

    @SerializedName("ES1800496542831234567890")
    @Expose
    public ES1800496542831234567890 eS1800496542831234567890;

}

public class Transaction {

    @SerializedName("idmovimiento")
    @Expose
    public String idmovimiento;
    @SerializedName("fechaoperacion")
    @Expose
    public String fechaoperacion;
    @SerializedName("fechavalor")
    @Expose
    public String fechavalor;
    @SerializedName("descripcion")
    @Expose
    public String descripcion;
    @SerializedName("importe")
    @Expose
    public String importe;
    @SerializedName("saldo")
    @Expose
    public String saldo;
    @SerializedName("orden")
    @Expose
    public String orden;
    @SerializedName("oficinaorigen")
    @Expose
    public String oficinaorigen;
    @SerializedName("conceptocomun")
    @Expose
    public String conceptocomun;
    @SerializedName("conceptopropio")
    @Expose
    public String conceptopropio;
    @SerializedName("documento")
    @Expose
    public String documento;
    @SerializedName("referencia1")
    @Expose
    public String referencia1;
    @SerializedName("referencia2")
    @Expose
    public String referencia2;
    @SerializedName("newreferencia1")
    @Expose
    public String newreferencia1;
    @SerializedName("newreferencia2")
    @Expose
    public String newreferencia2;
    @SerializedName("facturas")
    @Expose
    public String facturas;
    @SerializedName("documentos")
    @Expose
    public String documentos;
    @SerializedName("additional")
    @Expose
    public List<Additional> additional = new ArrayList<Additional>();

}
    
answered by 12.10.2016 в 21:15
0

I use Jackson:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>

For complex objects you will have to use something similar to this:

ObjectMapper mapper = new ObjectMapper();
Respuesta miRespuesta = mapper.readValue(json, new TypeReference<Respuesta() {
});

If this does not work for you, you should deserialize the List object independently:

List<Cuenta> miRespuesta = mapper.readValue(json, new TypeReference<List<Cuenta>>() {
    });
    
answered by 13.10.2016 в 10:24
0

The object is not deserialized because the structure is ill-defined. You must have something similar to:

public class objetoCompleto {
    public List<transaction> objTransaction;
}

public class additional {
    private String numComplementario;
    private String concepto1;
    private String concepto2;
}

public class transaction {
    private Long idmovimiento;
    private Date fechaoperacion;
    private Date fechavalor;
    private String descripcion;
    private BigDecimal importe;
    private BigDecimal saldo;
    private Integer orden;
    private String oficinaorigen;
    private String conceptocomun;
    private String conceptoPropio;
    private String documento;
    private String referencia1;
    private String referencia2;
    private String newreferencia1;
    private String newreferencia2;
    private int facturas;
    private int documentos;
    private List<Additional> additional;
}
    
answered by 13.10.2016 в 17:02