String deserialization

3

I got Retrofit the Drivers field from the following json:

{
  "Drivers": [
    {
      "DriverID": 0,
      "Latitude": -23.642276336,
      "Longitude": -46.634615118
    },
    {
      "DriverID": 1,
      "Latitude": -23.64227916,
      "Longitude": -46.634592381
    }
  ],
  "Success": true
}

I have a list:

List drivers = MyModel.getDrivers();

Then I made a drivers.get (0) .toString () and got the following String:

{DriverID=0.0, Latitude=-23.642259377, Longitude=-46.634618813}

Now I want to make a deserialize in this list so I have something like:

driver.getDriverID()

I tried this way, but it did not work:

Primary code:

Gson gson = new Gson();
Type listType = new TypeToken<List<Drivers>>(){}.getType();
String str = drivers.get(0).toString();
List<Drivers> teste = (List<Drivers>) gson.fromJson(str, listType);

Drivers.java:

public class Drivers {
    @SerializedName("DriverID")
    private Integer DriverID;

    public Integer getDriverID() {  
        return DriverID;
    }

    public void setDriverID(Integer driverID) {
        DriverID = driverID;
    }
}
    
asked by anonymous 22.01.2016 / 16:22

2 answers

3

Try this:

Gson gson = new Gson();
Type listType = new TypeToken<List<Drivers>>(){}.getType();
String str = drivers.get(0).toString();
Drivers teste =   gson.fromJson(str, Drivers.class);
teste.getDriverID();

How do you get just one item from the list:

String str = drivers.get(0).toString();

It will be just the element of it:

{DriverID=0.0, Latitude=-23.642259377, Longitude=-46.634618813}

Then your result will be Drivers

    
22.01.2016 / 16:41
3

The problem is that you are putting objeto inside array .

Given that drivers.get(0) returns a Driver object , your code needs to look something like:

Gson gson = new Gson();
String str = drivers.get(0).toString();
Drivers driver = gson.fromJson(str, Drivers.class);
    
22.01.2016 / 16:49