Hews
Hews

Reputation: 581

Parsing JSON in Retrofit using Gson

I have a JSON file with the following structure:

{
 "FLYWEIGHT": [
 {
 "name": "Henry Cejudo"
 },
 {
 "name": "Sergio Borg"
 },.........], 
 {...},
 ...]}

I'm struggling to parse this with Gson. I have the following structure for UfcRank and FighterList:

public class UfcRank {

@SerializedName("name")
private String name;
}


public class FighterList {

@SerializedName("FLYWEIGHT")
public List<UfcRank> FLYWEIGHT;

}

I use retrofit to parse through:

RankingsApi service = RankingsRestAdapter.getRetrofitInstance().create(RankingsApi.class);
Call<Fighterlist> call = service.getRankingsApi();

call.enqueue(new Callback<FighterList>() {
    @Override
    public void onResponse(Call<FighterList> call, Response<FighterList> response) {
    FighterList data = new Gson().fromJson(response.body().toString(), FighterList.class);

}

I have the following structure for RankingsApi and RankingsRestAdapter:

public interface RankingsApi {

@GET("last_ready_run/data?api_key=XXXXXX")
Call<FighterList> getRankingsApi();

}

public class RankingsRestAdapter {

public static final String RANKINGS_URL = "XXXXXXX"
public static Retrofit retrofit;

public static Retrofit getRetrofitInstance() {

if (retrofit == null) {
    retrofit = new retrofit2.Retrofit.Builder()
    .baseUrl(RANKINGS_URL)
    .addConverterFactor(GsonConverterFactory.create())
    .build();
}
return retrofit;
}
}

Now I receive the error:

Expected BEGIN_OBJECT but Was STRIng at line 1 column 1 path $

Is this due to how I'm structuring the UfcRank and FighterList classes?

Thanks! :)

Upvotes: 0

Views: 130

Answers (1)

Nabin Bhandari
Nabin Bhandari

Reputation: 16429

Since you have used GsonConverterFactory while building Retrofit instance, Gson parsing is already used and it provides you with the reference of your model class directly. You should not parse again.

@Override
public void onResponse(Call<FighterList> call, Response<FighterList> response) {
    if(response.isSuccessful() {
        FighterList data = response.body();
    } else {
        // Handle error.
    }
}

Upvotes: 2

Related Questions