简体   繁体   中英

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! :)

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.
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM