angel angel - 3 months ago 14
JSON Question

Gson Object complex with list objects (from json to complex object)

I got and error when I execute

VehiculoCombustiblesResponseDTO respuesta= new Gson().fromJson(response.toString(), VehiculoCombustiblesResponseDTO.class);


error is:


Unhandled exception: com.google.gson.JsonSyntaxException:
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was
BEGIN_ARRAY at line 1 column 52 path $.f


this is the json response

{"a":5,"b":50,"c":23,"d":"12349","e":2,"f":[{"a":2,"b":"Premium"},{"a":1,"b":"Magna"}]}


I have this class

public class VehiculoCombustiblesResponseDTO {
private int a;
private int b;

/**
* VehiculoId
* @return
*/
public int getA() {
return a;
}
/**
* VehiculoId
* @return
*/
public void setA(int a) {
this.a = a;
}

/**
* CapacidadCombustible
* @return
*/
public int getB() {
return b;
}

/**
* CapacidadCombustible
* @return
*/
public void setB(int b) {
this.b = b;
}

/**
* KilometrajeInicial
* @return
*/
public int getC() {
return c;
}
/**
* KilometrajeInicial
* @return
*/
public void setC(int c) {
this.c = c;
}

/**
* NumeroEconomico
* @return
*/
public String getD() {
return d;
}
/**
* NumeroEconomico
* @return
*/
public void setD(String d) {
this.d = d;
}

/**
* TipoCombustibleId
* @return
*/
public int getE() {
return e;
}
/**
* TipoCombustibleId
* @return
*/
public void setE(int e) {
this.e = e;
}
/**
* TiposCombustible (Listado)
* @return
*/
public TiposCombustibleResponseDTO getF() {
return f;
}
/**
* TiposCombustible (Listado)
* @return
*/
public void setF(TiposCombustibleResponseDTO f) {
this.f = f;
}

private int c;
private String d;
private int e;
private TiposCombustibleResponseDTO f;
}


and this other

public class TiposCombustibleResponseDTO {

/**
* obtiene CombustibleId del servidor
* @return
*/
public int getA() {
return a;
}

/**
* Establece CombustibleId
* @param a
*/
public void setA(int a) {
this.a = a;
}

/**
* obtiene Descripcion del servidor
* @return
*/
public String getB() {
return b;
}

/**
* Estaclece Descripcion del servidor
* @param b
*/
public void setB(String b) {
this.b = b;
}

private int a;
private String b;

}

Answer

You said to Gson: give me object from this JSON, Gson found a object, but the f in JSON response is an array, but in your class this field is an object, so this is incompatible.

There is significant difference between JSON object and array:

This is JSON object:

{ "firstName":"John", "lastName":"Doe" }

This is JSON array:

[
    { "firstName":"John", "lastName":"Doe" }, 
    { "firstName":"Anna", "lastName":"Smith" }, 
    { "firstName":"Peter","lastName":"Jones" }
]

Notice these brackets: []

Solution:

Change f field to an array:

private TiposCombustibleResponseDTO[] f;