简体   繁体   English

使用Gson在翻新中解析JSON

[英]Parsing JSON in Retrofit using Gson

I have a JSON file with the following structure: 我有一个具有以下结构的JSON文件:

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

I'm struggling to parse this with Gson. 我正在努力与Gson进行分析。 I have the following structure for UfcRank and FighterList : 我对UfcRankFighterList具有以下结构:

public class UfcRank {

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


public class FighterList {

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

}

I use retrofit to parse through: 我使用retrofit来解析:

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 : 我具有RankingsApiRankingsRestAdapter的以下结构:

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? 这是由于我如何构造UfcRankFighterList类吗?

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. 由于在构建Retrofit实例时使用了GsonConverterFactory ,因此已经使用了Gson解析,它可以直接为您提供模型类的引用。 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.
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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