Search code examples
javaandroidarraysjsonrobospice

Jackson - reading a JSON array with Robospice using loadDataFromNetwork() method


I'm trying to read JSON array, which has the following format: [{"vehicle_id":"76","color":"red"},{"vehicle_id":"7","color":"blue"}], following Robospice's Starter Guide.

Vehicle.java

public class Vehicle {
    @JsonProperty("vehicle_id")
    private int vehicleID;
    @JsonProperty("color")
    private String color;
}

(setters and getters follow)

Class which is giving errors: VehiclesRequest.class

public class VehiclesRequest extends SpringAndroidSpiceRequest<Vehicle> {

    private static final String METHOD = "systemVehicles";

    public SystemVehiclesRequest() {
        super(Vehicle.class);
    }

    @Override
    public Vehicle[] loadDataFromNetwork() throws Exception {
        return getRestTemplate().getForObject(
                FULL_URL,
                Vehicle[].class);
    }
}

As you can see, I'm overriding loadDataFromNetwork() method and then passing it to the spiceManager.execute() method inside my activity and reading data from the request using custom listener. However I cannot return and array (I've tried with the List<> too) from loadDataFromNetwork(), what would be the best workaround here? I know I could get the data in a different way but I want to still use my listener and be able to make try block that way.


Solution

  • I solved the problem by adding Vehicles class:

    @JsonIgnoreProperties(ignoreUnknown = true)
    public class Vehicles extends ArrayList<Vehicle> {
    
        public Vehicles() {
        }
    
    }
    

    and changing loadDataFromNetwork() method like that:

    public Vehicles loadDataFromNetwork() throws Exception {
        return getRestTemplate().getForObject(
                FULL_URL,
                Vehicles.class);
    }