我有一个JSON:
{
"Bills": {
"name": "Mr.X",
"creditCardNumber": "1234567890",
"billDetails": [{
"PaymentDueDate": "07-03-2018",
"StatementDate": "24-02-2018",
"AmountDue": "2156"
},
{
"PaymentDueDate": "05-02-2018",
"StatementDate": "23-01-2018",
"AmountDue": "3256"
},
{
"PaymentDueDate": "07-01-2018",
"StatementDate": "24-12-2017",
"AmountDue": "1132"
},
{
"PaymentDueDate": "07-12-2017",
"StatementDate": "24-10-2017",
"AmountDue": "7654"
}
]
}
}
我正在尝试读取JSON对象,但JSONArray却为null,即billDetailsArr
public static void readJSONFile() throws java.text.ParseException {
JSONParser parser = new JSONParser();
JSONObject data;
try {
data = (JSONObject) parser.parse(new FileReader("\\Bills.json"));
JSONArray billdetailsArr = (JSONArray) data.get("billDetails");
for(int i=0;i<data.size();i++)
{
JSONObject jsonobj_2 = (JSONObject) billdetailsArr.get(i);
String dateStr = (String) jsonobj_2.get(new Date("StatementDate"));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date StatementDate = sdf.parse(dateStr);
}
}
我的POJO课是:
public class BillDetails {
private Date PaymentDueDate;
private Date StatementDate;
private String AmountDue;
}
我想要日期格式的StatementDate和PaymentDueDate不是字符串。我的代码正确吗?
最佳答案
billDetails数组不是根元素的属性-它是bills元素内的元素。因此,您需要获取bills元素,然后从中获取billsDetail数组。
例如
data = (JSONObject) parser.parse(new FileReader("\\Bills.json"));
JSONObject billsObj = (JSONObject)data.get("bills");
JSONArray billdetailsArr = (JSONArray)billsObj.get("billDetails");