0

I am reading a JSON like this:

{
"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"
    }
}]
}

I must say that the JSON is valid. I am consuming this JSON through an API. I can correctly read the properties "id", "utc" and "status", but I could not with "score", "awayTeam" and "homeTeam". I don't really know how to work those properties. I'd like to handle each propertie of score, awayTeam, and homeTeam individually, for example, I want to get just the name of awayTeam and homeTeam and the 2 properties of score.

This, is my code:

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());
            }
        });
    }
}

Now this is my interface. footballdataService

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

This is PartidosRespuestas class

public class PartidosRespuesta {
    private ArrayList<Partido> matches;

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

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

This, is the adapter.

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

And this.., is Partido class

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 Answers 3

1

POJO classes of your code should this:

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

}

Edit:

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

}

And tool convert json to java code: http://www.jsonschema2pojo.org/

Sign up to request clarification or add additional context in comments.

1 Comment

Partido p = dataset.get(position); HomeTeam homeTeam = p.getHomeTeam(); String nameHomeTeam = homeTeam.getName()
0

try

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

1 Comment

Yeah.., I've got it at the end of Partidos class file
0

It's seems like you've problems with your models. Use this link to convert your json to java object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.