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

I am trying to read a JSON array that has the following format: [{"vehicle_id":"76","color":"red"},{"vehicle_id":"7","color":"blue"}] , after Robospice Beginner's Guide .

Vehicle.java

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

(setters and getters follow)

Class that gives 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 override the loadDataFromNetwork() method and then pass it to the spiceManager.execute() method inside my activity and read the data from the request using a custom listener. However, I cannot return the array (I also tried using List<> ) from loadDataFromNetwork() , what would be the best workaround here? I know I can get the data in a different way, but I want to still use my listener and be able to make the try block this way.

+3
source share
2 answers

I solved the problem by adding the Vehicles class:

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

and change the way loadDataFromNetwork() as follows:

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

Noticed that you should pass an array of type to the 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 this looks reasonable using an array type than creating a new class extending ArrayList<Vehicle> to make everything work.

0
source

All Articles