从JSONObject返回时,JSONArray为null

时间:2018-03-14 11:37:34

标签: java json

我有一个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&amp;日期格式的PaymentDueDate不是String。我的代码是否正确?

1 个答案:

答案 0 :(得分:1)

billDetails数组不是根元素的属性 - 它是bill元素中的元素。因此,您需要获取bill元素,然后将billsDetail数组关闭。

e.g。

data = (JSONObject) parser.parse(new FileReader("\\Bills.json"));
JSONObject billsObj = (JSONObject)data.get("bills");
JSONArray billdetailsArr = (JSONArray)billsObj.get("billDetails");