String deserialization

Asked

Viewed 103 times

3

I caught the Retrofit 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();

So 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 an deserialize on that list so I have something like:

driver.getDriverID()

I tried this way, but it didn’t work:

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

Java drivers.:

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

    public Integer getDriverID() {  
        return DriverID;
    }

    public void setDriverID(Integer driverID) {
        DriverID = driverID;
    }
}

2 answers

3


Try it this way:

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 pick only one item from the list:

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

He will only be her element:

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

Then your result will be one Drivers

  • 1

    I was so focused on catching with Array that I had forgotten that it was much easier to pick up as Object. Thank you! I just added in the drivers.class the getLatitude and getLongitude and it was working exactly as I wanted. Note: listType does not need to be used in this case, so I removed this line

3

The problem is that you’re putting one objeto within a array.

In view of the fact 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);
  • That’s right, it was much easier to do by Object and I tried to use Array. In his example only lacked to put the getDriverID that Thiago Luiz cited

Browser other questions tagged

You are not signed in. Login or sign up in order to post.