In my app I fetch a JSONArray
from a server. The received data has this structure:
[
{
"MatchID": 51170,
"Team1": {
"TeamId": 1,
},
"Team2": {
"TeamId": 1,
},
"Goals": [
{
"GoalID": 1,
},
{
"GoalID": 2,
},
{
"GoalID": 3,
}
]
}
]
The problem I have is that the JSONArray
'goals' inside it has an unknown length. I usually store and process all the data through getter and setters, like this:
public String getGoalid() {
return goalid;
}
public void setGoalid(String goalid) {
this.goalid = goalid;
}
But like this I just get the information of the last goal. I also tried to use the getter and setter as a string array, but like this I just stored the last value as well. What's the right way to store these unknown amout of strings correctly otherwise?
Edit:
Here's the code of how I process the received data:
List<GetData> GetData1 = new ArrayList<>();
public void Process(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetData GetData2 = new GetData();
JSONObject json = null;
try {
json = array.getJSONObject(i);
JSONObject team1 = json.getJSONObject("Team1");
JSONObject user = json.getJSONObject("Team2");
GetData2.setTeam1(team1.getString(TEAM1));
GetData2.setTeam2(user.getString(TEAM2));
JSONArray jArrayGoals = json.getJSONArray("Goals");
if(jArrayGoals == null || jArrayGoals.length() == 0){
}else {
for (int j = 0; j < jArrayGoals.length(); j++) {
JSONObject json_data = jArrayGoals.getJSONObject(j);
GetData2.setGoalid(json_data.getString("GoalID"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
GetData1.add(GetData);
}
}
I prefer use Gson
( https://github.com/google/gson )
Gradle install
dependencies {
implementation 'com.google.code.gson:gson:2.8.5'
}
for this case with classes like this
public class Team
{
private int TeamId;
public int getTeamId() { return this.TeamId; }
public void setTeamId(int TeamId) { this.TeamId = TeamId; }
}
public class Goal
{
private int GoalID;
public int getGoalID() { return this.GoalID; }
public void setGoalID(int GoalID) { this.GoalID = GoalID; }
}
public class RootObject
{
private int MatchID;
public int getMatchID() { return this.MatchID; }
public void setMatchID(int MatchID) { this.MatchID = MatchID; }
private Team Team1;
public Team getTeam1() { return this.Team1; }
public void setTeam1(Team1 Team1) { this.Team1 = Team1; }
private Team Team2;
public Team getTeam2() { return this.Team2; }
public void setTeam2(Team2 Team2) { this.Team2 = Team2; }
private ArrayList<Goal> Goals;
public ArrayList<Goal> getGoals() { return this.Goals; }
public void setGoals(ArrayList<Goal> Goals) { this.Goals = Goals; }
}
To get goals length will like this
RootObject rootObject = gson.fromJson(json, RootObject.class);
int goalLength = rootObject.getGoals().size()
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.