Android嵌套对象和Retrofit2

时间:2018-08-23 02:49:05

标签: android json api gson retrofit2

我正在读取这样的JSON:

{
"matches": [{
    "id": 246119,
    "utcDate": "2018-08-17T18:15:00Z",
    "status": "FINISHED",
    "homeTeam": {
        "id": 298,
        "name": "Girona FC"
    },
    "awayTeam": {
        "id": 250,
        "name": "Real Valladolid CF"
    },
    "score": {
        "winner": "DRAW",
        "duration": "REGULAR"
    }
}]
}

我必须说JSON有效。我正在通过API使用此JSON。我可以正确读取属性“ id”,“ utc”和“ status”,但无法使用“得分”,“ awayTeam”和“ homeTeam”。我真的不知道如何使用这些属性。我想分别处理score,awayTeam和homeTeam的每个属性,例如,我只想获得awayTeam和homeTeam的名称以及score的2个属性。

这是我的代码:

MainActivity

public class MainActivity extends AppCompatActivity {

    private Retrofit retrofit;
    private static final String TAG = "Football";
    private RecyclerView recyclerView;
    private ListaPartidosAdapter listaPartidosAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
        listaPartidosAdapter = new ListaPartidosAdapter(this);
        recyclerView.setAdapter(listaPartidosAdapter);
        recyclerView.setHasFixedSize(true);
        final LinearLayoutManager layoutManager = new LinearLayoutManager(this, VERTICAL, true);
        recyclerView.setLayoutManager(layoutManager);

        retrofit = new Retrofit.Builder()
                .baseUrl("http://api.football-data.org/v2/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        obtenerDatos();
    }

    private void obtenerDatos() {

        footballdataService service = retrofit.create(footballdataService.class);
        Call<PartidosRespuesta> partidosRespuestaCall = service.obtenerlistaPartidos();

        partidosRespuestaCall.enqueue(new Callback<PartidosRespuesta>() {
            @Override
            public void onResponse(Call<PartidosRespuesta> call, Response<PartidosRespuesta> response) {
                if(response.isSuccessful()) {
                    PartidosRespuesta partidosRespuesta = response.body();
                    ArrayList<Partido> listaPartidos = partidosRespuesta.getMatches();

                    listaPartidosAdapter.adicionarListaPartidos(listaPartidos);

                }
                else {
                    Log.e(TAG, "onResponse: " + response.errorBody());
                }
            }

            @Override
            public void onFailure(Call<PartidosRespuesta> call, Throwable t) {
                Log.e(TAG, "onFailure: " + t.getMessage());
            }
        });
    }
}

现在这是我的界面。 footballdataService

public interface footballdataService {
    @GET("competitions/2014/matches")
    Call<PartidosRespuesta> obtenerlistaPartidos();
}

这是PartidosRespuestas类

public class PartidosRespuesta {
    private ArrayList<Partido> matches;

    public ArrayList<Partido> getMatches() {
        return matches;
    }

    public void setMatches(ArrayList<Partido> matches) {
        this.matches = matches;
    }
}

这是适配器。

public class ListaPartidosAdapter extends RecyclerView.Adapter<ListaPartidosAdapter.ViewHolder> {

    private static final String TAG = "Football_Adapter";
    private ArrayList<Partido> dataset;
    private Context context;

    public ListaPartidosAdapter(Context context) {
        this.context = context;
        dataset = new ArrayList<Partido>();
    }

    @Override
    public ListaPartidosAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_partidos, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ListaPartidosAdapter.ViewHolder holder, int position) {
        Partido p = dataset.get(position);
        holder.status.setText(p.getId());
    }

    @Override
    public int getItemCount() {
        return dataset.size();
    }

    public void adicionarListaPartidos(ArrayList<Partido> listaPartidos){
        dataset.addAll(listaPartidos);
        notifyDataSetChanged();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private TextView status;

        public ViewHolder(View itemView) {
            super(itemView);

            status = (TextView) itemView.findViewById(R.id.status);
        }
    }
}

这是Partido类

public class Partido {
    private String id;
    private String utcDate;
    private String status;
    private EquipoCasa homeTeam;
    private EquipoVisita AwayTeam;
    private Puntaje score;

    public String getId() {
        return id;
    }

    public String getUtcDate() {
        return utcDate;
    }

    public String getStatus() {
        return status;
    }

    public EquipoCasa getHomeTeam() {
        return homeTeam;
    }

    public EquipoVisita getAwayTeam() {
        return AwayTeam;
    }

    public Puntaje getScore() {
        return score;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setUtcDate(String utcDate) {
        this.utcDate = utcDate;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public void setHomeTeam(EquipoCasa homeTeam) {
        this.homeTeam = homeTeam;
    }

    public void setAwayTeam(EquipoVisita awayTeam) {
        AwayTeam = awayTeam;
    }

    public void setScore(Puntaje score) {
        this.score = score;
    }

    public class EquipoCasa {

        private String id;
        private String name;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    public class EquipoVisita {
        private String id;
        private String name;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    public class Puntaje {
        private String winner;
        private String duration;

        public String getWinner() {
            return winner;
        }

        public void setWinner(String winner) {
            this.winner = winner;
        }

        public String getDuration() {
            return duration;
        }

        public void setDuration(String duration) {
            this.duration = duration;
        }
    }
}

3 个答案:

答案 0 :(得分:1)

您的代码的POJO类应该这样做:

AwayTeam.java

//AwayTeam
public class AwayTeam {

   @SerializedName("id")
   @Expose
   private Integer id;
   @SerializedName("name")
   @Expose
   private String name;

   public Integer getId() {
      return id;
   }

   public void setId(Integer id) {
      this.id = id;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

}

PartidosRespuesta.java

//Object response
public class PartidosRespuesta {

   @SerializedName("matches")
   @Expose
   private List<Match> matches = null;

   public List<Match> getMatches() {
      return matches;
   }

   public void setMatches(List<Match> matches) {
      this.matches = matches;
   }

}

HomeTeam.java

//HomeTeam
public class HomeTeam {

   @SerializedName("id")
   @Expose
   private Integer id;
   @SerializedName("name")
   @Expose
   private String name;

   public Integer getId() {
      return id;
   }

   public void setId(Integer id) {
      this.id = id;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

}

Score.java

//Score
public class Score {

   @SerializedName("winner")
   @Expose
   private String winner;
   @SerializedName("duration")
   @Expose
   private String duration;

   public String getWinner() {
      return winner;
   }

   public void setWinner(String winner) {
      this.winner = winner;
   }

   public String getDuration() {
      return duration;
   }

   public void setDuration(String duration) {
      this.duration = duration;
   }

}

编辑:

@Override
public void onBindViewHolder(ListaPartidosAdapter.ViewHolder holder, int position) {
    Partido p = dataset.get(position);
    HomeTeam homeTeam = p.getHomeTeam();
    String nameHomeTeam = homeTeam.getName();

}

然后工具将json转换为Java代码:http://www.jsonschema2pojo.org/

答案 1 :(得分:0)

尝试

public class Puntaje {
    public String winner;
    public String duration;
}

答案 2 :(得分:0)

似乎您的模型有问题。使用此linkjson转换为java对象。