Reputation: 582
I'm trying to parse some JSON, but I'm having a little trouble.
the JSON:
{
"CashGames": {
"Record": [
{
"_id": "1",
"Game": "No Limit Holdem",
"BlindAmounts": "1/3",
"MinBuyin": "100",
"MaxBuyin": "300",
"CasinoID": "1",
"MiscNotes": "",
"MoreNotes": ""
},
{
"_id": "2",
"Game": "No Limit Holdem",
"BlindAmounts": "2/5",
"MinBuyin": "200",
"MaxBuyin": "1000",
"CasinoID": "1",
"MiscNotes": "aria",
"MoreNotes": ""
}
]
}}
the class that defines it:
public class RecordResponse {
public Record records;
public class Record {
public List<Result> results;
}
public static class Result {
@SerializedName("Game")
public String Game;
@SerializedName("BlindAmounts")
public String BlindAmounts;
@SerializedName("MinBuyin")
public String MinBuyin;
@SerializedName("MaxBuyin")
public String Maxbuyin;
@SerializedName("CasinoID")
public long CasinoID;
@SerializedName("MiscNotes")
public String MiscNotes;
@SerializedName("MoreNotes")
public String MoreNotes;
}
}
and what I'm trying to do to parse it:
RecordResponse cashResponse = gson.fromJson(cashRecords, RecordResponse.class);
List<Result> results = cashResponse.records.results;
for (Result cashResult : results){
Log.e("log_test", cashResult.Game);
}
but i get a NullPointerException when I try to declare results (the List). What am I doing wrong?
Upvotes: 2
Views: 2272
Reputation: 66935
Your JSON structure simply does not match the Java data structure.
Here is an example with a Java data structure that matches the JSON structure in the original question.
import java.io.FileReader;
import java.util.List;
import com.google.gson.Gson;
public class Foo
{
public static void main(String[] args) throws Exception
{
Gson gson = new Gson();
RecordResponse cashResponse = gson.fromJson(new FileReader("input.json"), RecordResponse.class);
System.out.println(gson.toJson(cashResponse));
List<Result> results = cashResponse.CashGames.Record;
for (Result cashResult : results)
{
System.out.println(cashResult.Game);
}
}
}
class RecordResponse
{
CashGamesContainer CashGames;
}
class CashGamesContainer
{
List<Result> Record;
}
class Result
{
String _id;
String Game;
String BlindAmounts;
String MinBuyin;
String Maxbuyin;
long CasinoID;
String MiscNotes;
String MoreNotes;
}
Upvotes: 2