Question

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.

Était-ce utile?

La 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);
}

Autres conseils

Noticed that you should pass array type to super constructor:

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);
    }
}

And I think it looks much reasonable using an array type than creating a new class extending ArrayList<Vehicle> to get things work.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top