我正在尝试解析一些JSON,但我遇到了一些麻烦。
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": ""
}
]
}}
定义它的类:
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;
}
}
以及我正在尝试解析它:
RecordResponse cashResponse = gson.fromJson(cashRecords, RecordResponse.class);
List<Result> results = cashResponse.records.results;
for (Result cashResult : results){
Log.e("log_test", cashResult.Game);
}
但是当我尝试声明结果(List)时,我得到一个NullPointerException。我做错了什么?
答案 0 :(得分:2)
您的JSON结构与Java数据结构不匹配。
这是一个Java数据结构的示例,它与原始问题中的JSON结构相匹配。
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;
}